I saw so many of these questions, and I was looking for a solution to the same problem regardless of the platform, which does not allow to collide with firewalls or get into the socket.
So here is what I did:
import java.io.File; import java.io.IOException; public class SingleInstanceLock { private static final String LOCK_FILEPATH = System.getProperty("java.io.tmpdir") + File.separator + "lector.lock"; private static final File lock = new File(LOCK_FILEPATH); private static boolean locked = false; private SingleInstanceLock() {} public static boolean lock() throws IOException { if(locked) return true; if(lock.exists()) return false; lock.createNewFile(); lock.deleteOnExit(); locked = true; return true; } }
Using System.getProperty ("java.io.tmpdir") for the lockfile path ensures that you will always create your lock in one place.
Then from your program, you simply call something like:
blah blah main(blah blah blah) { try() { if(!SingleInstanceLock.lock()) { System.out.println("The program is already running"); System.exit(0); } } catch (IOException e) { System.err.println("Couldn't create lock file or w/e"); System.exit(1); } }
And that does it for me. Now, if you kill the program, it will not delete the lock file, but you can solve this problem by writing the PID code of the program in the lock file and making the lock () method if this process is already running. This is left as an assumption for everyone who is interested. :)
Nirro Mar 06 '14 at 12:56 2014-03-06 12:56
source share