简体   繁体   中英

How can we make sure that only one instance of any application in running even in 2 different JVM's

I was asked this question at an interview. Lets say VLC player is there and running on our OS. Now when we again try to launch VLC , that should not happen.

alternatively, say we have two command windows, we runn same java program in two different Windows. How can we ensure only one runs.

Is this OS dependent thing? Whats implementation?

I read something about MUTEX/Semaphore but I guess that is inside one JVM only.

You could write a pid file to disk, in a known location, indicating that the application is already running. Then, on startup, look for that file. If it's there, the application is already running, so exit.

Left as an exercise to the reader: ensuring that the pid file is removed even when the app crashes.

One possible answer would be to open and listen on a specific (and uncommon) tcp server port on start-up, since only one process can hold the socket at a time a second instance could detect the socket can't be listen'd and then exit with an error. Alternatively, you could potentially create a File on startup (and exit if it exists).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM