How can we ensure that only one instance of any application is running even in two different JVMs?

I was asked this question in an interview. Let's say a VLC player exists and runs on our OS. Now, when we try to launch VLC again, this shouldn't happen.

let's say we have two command windows, we are running the same java program on two different windows. How can we ensure only one launch.

Does it depend on the OS? What is implementation?

I have read a thing or two about MUTEX / Semaphore, but I think this is only inside one JVM.


source to share

2 answers

You can write the pid file to disk at a known location, indicating that the application is already running. Then, on startup, find this file. If it's there, the app is already running, so exit.

Left as an exercise for the reader: make sure the pid file is removed even if the application crashes.



One possible answer would be to open and listen on a specific (and unusual) port of the tcp server at startup, since only one process can hold the socket at a time when the second instance could detect that the socket could not be listened to 'd and then exit with an error. Alternatively, you can create File

at startup (and exit if it exists).



All Articles