5

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.

Arvind
  • 6,404
  • 20
  • 94
  • 143
  • Can you change the implementation of the "specific Jar"? – Grim Dec 13 '12 at 11:45
  • its highly unlikely-- this jar will basically be used to connect to a server and get/run some code via RMI... – Arvind Dec 13 '12 at 11:53
  • even though if you can get sure that the jar is running in the current jvm, you cant get sure that there are other jvm's who running the jar using different users or different jdk's (ie openjdk). Sorry. – Grim Dec 13 '12 at 12:01
  • @PeterRader i will initialise and terminate each machine that will be running this jar-- and no one else will have access to those machines (that run this single jar)... – Arvind Dec 13 '12 at 12:10

2 Answers2

6

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
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • I went to the jps docs-- there it is given that "NOTE: You are advised not to write scripts to parse jps output since the format may change in future releases. If you choose to write scripts that parse jps output, expect to modify them for future releases of this tool." -- can you suggest some other way where I don't need to be worried about change in output formats? Maybe a pure shellscript command(or java command)? Thanks... – Arvind Dec 13 '12 at 10:57
3

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.

Grim
  • 1,938
  • 10
  • 56
  • 123