Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 650
Arvind Avatar asked Dec 13 '12 10:12

Arvind


People also ask

How do I know if a JAR is running?

To test this, pick a .exe file you see running in Task Manager and test out the cmd line. That means there is no task running equal to java.exe .

How do you check if a script is already running?

An easier way to check for a process already executing is the pidof command. Alternatively, have your script create a PID file when it executes. It's then a simple exercise of checking for the presence of the PID file to determine if the process is already running. #!/bin/bash # abc.sh mypidfile=/var/run/abc.

Is JAR already compiled?

jar file contains compiled code (*. class files) and other data/resources related to that code. It enables you to bundle multiple files into a single archive file.

How do you check if any Java JAR file is running in the background in Windows?

You can use the jvisualvm which is within the jdk: %JAVA_HOME%/bin/jvisualvm . its an oracle-specific tool, users of any OpenJDK do not have it.


2 Answers

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
like image 194
Brian Agnew Avatar answered Sep 25 '22 08:09

Brian Agnew


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.

like image 20
Grim Avatar answered Sep 22 '22 08:09

Grim