3

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?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154

2 Answers2

2

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"));
}
David Conrad
  • 15,432
  • 2
  • 42
  • 54
2

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;
}
spongebob
  • 8,370
  • 15
  • 50
  • 83
  • It's faster if you don't have to catch an exception. In my original answer, I was using Class.forName and catching an exception, but I refactored it to avoid that. – David Conrad Dec 17 '20 at 07:09
  • @DavidConrad Once Project Loom is released, it will be enough to check the Java version. Regarding performance, note that `Class#getDeclaredMethods()` creates a copy of the array, while `Class#getDeclaredMethod()` does not. In my benchmark the difference is negligible, if any. – spongebob Dec 18 '20 at 00:55
  • If you care about performance - cache the result. – Johannes Kuhn Dec 24 '20 at 05:16