java/shellscript code to find out if a jar file is already running on current machine

随声附和 提交于 2019-11-29 21:32:59

问题


How do I find out if a specific JAR file is running on my machine or not? I just want to ensure that a specific JAR is only executed once at any time-- so if another request to execute the same jar comes in then I should not again invoke that jar.

I can use code for the above either as java code (which I will add to that JAR itself) or as shellscript (which I will use to invoke the jar file).

The machine will be a Linux machine-- either CentOS, or Debian or Ubuntu or Amazon Linux.


回答1:


jps is a simple command-line tool that prints out the currently running JVMs and what they're running. You can invoke this from a shell script.

jps -l will dump out the JVM process id and the main class that it's executing. I suspect that's the most appropriate for your requirement.

Noting your comment re. jps being not supported, if it's a valid worry that you can't easily mitigate via testing when you upgrade a JDK/JRE, then perhaps use something like:

pgrep -lf java



回答2:


Try to create a new jar,

create a class inside with like this (not yet functional code, just a scribble):

static ServerSocket unicorn;
public void load(){
    unicorn=new ServerSocket(39483); // whatever-port

    URLClassLoader myloader = new URLClassLoader(new URL[]{this.getClass().getResource("/META-INF/specific.jar")});
    ... // do all your unique stuff
    Runtime.addShutdownHook(new Runnable(){unicorn.close();})
}

Place your specific.jar inside the new.jar. If ever another instance of this jar try to be load, a exception will be thrown: Socket already in use.



来源:https://stackoverflow.com/questions/13857979/java-shellscript-code-to-find-out-if-a-jar-file-is-already-running-on-current-ma

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!