Swing 应用程序的 Graal 本机图像:在图像堆中检测到启动的线程

Graal native-image of swing app: Detected a started Thread in the image heap

public class SimpleApp {
    public static void main( String[] args ) {
        JOptionPane.showMessageDialog(null, "Ciao", "Info", JOptionPane.INFORMATION_MESSAGE);
    }
} 

当我尝试使用 native-image --no-fallback 创建原生图像时,我得到了这个:

Error: Detected a started Thread in the image heap. Threads running in the image generator are no longer running at image run time. The object was probably created by a class initializer and is reachable from a static field. By default, all class initialization is done during native image building.You can manually delay class initialization to image run time by using the option -H:ClassInitialization=. Or you can write your own initialization methods and call them explicitly from your main entry point.

Detailed message: Trace: object sun.java2d.opengl.OGLRenderQueue field sun.java2d.opengl.OGLRenderQueue.theInstance

这都与何时应初始化 class 有关——GraalVM 团队有一篇关于此主题的更新文章: https://medium.com/graalvm/updates-on-class-initialization-in-graalvm-native-image-generation-c61faca461f7

简短版本:使用跟踪(在比你的版本更新的 Graal 包中添加)找到所谓的有问题的 class,然后将它们设置为在 运行 时间初始化。说起来容易,做起来难。 对于它的价值,我只是在 19.2(企业)版本和一些包含 AWT 的随机代码中遇到了同样的问题。不过,消息已更改(为清楚起见略作编辑):

Error: Detected a started Thread in the image heap. Threads running in the image generator are no longer running at image run time. To see how this object got instantiated use -H:+TraceClassInitialization. The object was probably created by a class initializer and is reachable from a static field. You can request class initialization at image run time by using the option --initialize-at-build-time=<class-name>. Or you can write your own initialization methods and call them explicitly from your main entry point. Trace: object sun.awt.AWTAutoShutdown method sun.awt.AWTAutoShutdown.getInstance()

我会解决这个问题(可能从 "Hello World" 的 AWT 等价物开始,如果我成功了,我会用具体的细节更新我的答案。Google 到处都是原生图像的例子,而不是与 Swing/AWT/JavaFX 一起工作,所以我不确定我是否会成功。

免责声明:我在 Oracle 工作,但不在与 Graal 开发人员关系密切的组织中(可能没有共同的经理)。我说的都是我的意见。