Johnydep
Johnydep

Reputation: 6277

Running only single instance of Executable Jar file

So i have packaged my project as a single executable jar that works fine. But at times it happens that the user launches the file multiple times, and this causes it to launch multiple instances of same project (causing unexpected behavior e.g overwriting values in files by delayed instances of project).

I want to know for a windows platform (Win7), what are the options to lock the execution for only one time, and then if the jar is already running, simply don't proceed executing the code again.

I read about Process ID's but if there are multiple java app's they all end up showing imagename as javaw.exe and how can i determine own process id??

Please suggest what is the proper way of doing this thing, thank you!!

Upvotes: 2

Views: 2616

Answers (3)

ndeverge
ndeverge

Reputation: 21564

You can open a ServerSocket on a dedicated TCP port at your application start-up, and close it at your application shutdown.

If an instance is already running, you'll get a "Port in use" exception.

Upvotes: 1

Radu Cugut
Radu Cugut

Reputation: 1673

Based on my experience, the best approach I used was to create a listening ServerSocket on a specific port (like 61234). The socket doesn't do anything, but if you manage to create it, it means that no other process has been started. The duplicated instances of the executable jar file will fail to create a ServerSocket on the same port and so they should exit.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533930

The simplest solution is to use a fixed, unused port.

ServerSocket ss;
try {
    ss = new ServerSocket(MY_PORT);
    // not already running.
} catch (BindException e) {
    // already running.
}

Upvotes: 3

Related Questions