且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何替换当前的Java进程,比如unix风格的exec?

更新时间:2023-12-04 07:48:58

这是一种复杂但便携的方式。

Here is a complicated, but portable, way.

将代码拆分为两个罐子。一个非常小的jar就是为了管理流程启动。它创建一个ClassLoader,在其类路径上保存另一个jar。

Split your code into two jars. One very small jar is there just to manage process startup. It creates a ClassLoader that holds the other jar on its classpath.

当你想加载一个新版本时,你终止从旧jar运行代码的所有线程。从旧jar中取消对类实例的所有引用。取消对加载旧jar的ClassLoader的所有引用。此时,如果您没有遗漏任何内容,旧类和ClassLoader应该有资格进行垃圾回收。

When you want to load a new version, you terminate all threads running code from the old jar. Null out all references to instances of classes from the old jar. Null out all references to the ClassLoader that loaded the old jar. At this point, if you didn't miss anything, the old classes and ClassLoader should be eligible for garbage collection.

现在重新开始使用指向的新ClassLoader实例新的jar,然后重新启动你的应用程序代码。

Now you start over with a new ClassLoader instance pointing at the new jar, and restart your application code.