如何替换当前的Java进程,比如unix风格的exec? [英] How can I replace the current Java process, like a unix-style exec?

查看:125
本文介绍了如何替换当前的Java进程,比如unix风格的exec?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用Java编写的服务器作为Windows服务运行(感谢Install4J)。我希望此服务能够下载其运行的最新版本的JAR文件,并开始运行新代码。缝合是我不希望Windows服务完全退出。

I have a server written in Java that runs as a Windows service (thanks to Install4J). I want this service to be able to download the latest version of the JAR file it runs from, and start running the new code. The stitch is that I don't want the Windows service to fully exit.

理想情况下,我会通过unix样式的exec()调用来完成此操作以停止当前版本并运行新的。我怎样才能最好地完成这个?

Ideally, I would accomplish this by a unix-style exec() call to stop the current version and run the new one. How can I best accomplish this?

推荐答案

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

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.

这篇关于如何替换当前的Java进程,比如unix风格的exec?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆