Start Java program only if not already running

Morinar picture Morinar · Mar 18, 2009 · Viewed 23.6k times · Source

I need to start 1-3 external programs in my Java application that have paths defined by the user. I have few requirements:

  1. I don't want the program to execute if it is already running

  2. I don't want any of the programs to steal focus from my Java application

  3. I don't care if any of them fail to start or not. They just need to fail silently.

Here is what I have come up with so far:

ProcessBuilder pb = new ProcessBuilder(userDefinedPath1);
try {
    pb.start();
}
catch (Exception e) {
    // Something went wrong, just ignore
}

And then I repeat that 3 more times with the other two paths. This starts like I would expect and meets my third requirement just fine, but fails on the first two.

What is the best way to do this?

Edit:

  1. I don't have any control of these other apps. They are third party. Also, they could have been start or stopped by the user manually at any time.

  2. I know the exact names of the executables (e.g. "blah.exe") and they will always be the same, but the paths to the executables won't necessarily be.

  3. Batch file wrappers are not feasible here.

  4. The other apps are not java apps, just plain old Windows executables.

Answer

nathanfranke picture nathanfranke · Aug 14, 2017

In order to avoid potential lock file / crash issues, it is possible to start a server and catch the port collision. These servers are automatically stopped on system shutdown (Even after a crash)

public static ServerSocket ss;

public static void main (String[] args) {

    ss = null;

    try {
        ss = new ServerSocket(1044);
    } catch (IOException e) {
        System.err.println("Application already running!");
        System.exit(-1);
    }
}