在运行时检测ProjectLoom技术是否丢失或存在JVM



Project Loom现在可以在Java 16的特殊早期版本中使用。

如果我在缺乏Project Loom技术的Java实现上运行我的基于Loom的应用程序,有没有一种方法可以在我的应用程序启动的早期优雅地检测到这一点?

我想写这样的代码:

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

如何实现projectLoomIsPresent()方法?

方法1:

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

方法2:

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

您可以检查Project Loom:之前不存在的功能

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

不需要捕捉异常:

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"));
}

最新更新