Detect Project Loom technology as missing or present JVM at runtime

199 views Asked by At

Project Loom is now available in special early-release builds of Java 16.

If I were to run my Loom-based app on a Java implementation lacking in the Project Loom technology, is there a way to detect that gracefully early in my app launching?

I want to write code something like this:

if( projectLoomIsPresent() )
{
    … proceed …
}
else
{
    System.out.println( "ERROR - Project Loom technology not present." ) ;
}

How might I implement a projectLoomIsPresent() method?

2

There are 2 answers

3
spongebob On BEST ANSWER

Method 1:

return System.getProperty("java.version").contains("loom");

Method 2:

try {
    Thread.class.getDeclaredMethod("startVirtualThread", Runnable.class);
    return true;
} catch (NoSuchMethodException e) {
    return false;
}
0
David Conrad On

You could check for features not present before Project Loom:

import java.util.Arrays;

public static boolean projectLoomIsPresent() {
    return Arrays.stream(Thread.class.getClasses())
        .map(Class::getSimpleName)
        .anyMatch(name -> name.equals("Builder"));
}

There's no need to possibly catch an exception:

import java.lang.reflect.Method;
import java.util.Arrays;

public static boolean projectLoomIsPresent() {
    return Arrays.stream(Thread.class.getDeclaredMethods())
        .map(Method::getName)
        .anyMatch(name -> name.equals("startVirtualThread"));
}