This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
im asking myself how is it possible to detect if an instance of an application is already running.
i know i could create a .lock file which is created when the application starts, and, if another instance is created checks for that file (and aborts if it exists).
But this is imo a workaround and not a good way to do this.
Is there any way to check which applications are running in the JVM?
With JNI you could check both the available windows and the running processes. Both have their drawbacks.
- Listing the available windows really does that - list the available windows. That includes any dialogs. Programs without any windows will not show up.
- Listing the running processes does not work well with Java, because the process executable is java.exe or javaw.exe. There is no way to make a distinction between two different programs both launched by a JVM.
That's why lock files or a server socket are often used in Java to find out if there already is another instance of the same program running. Native programs usually use the second technique which works fine because they each have their own application name. This is not fail safe either though since a) two different programs can share the same executable name, and b) by using a renamed copy of the executable this check can be prevented.
Rob Prime wrote:Native programs usually use the second technique which works fine because they each have their own application name.
There are quite a few native programs that still use the first technique, which can be a better solution.
For example: the Apache HTTPD server and MySQL and Postgres all use lock files (and this list is certainly not exhaustive).
IMHO this is a better technique as it allows the possibility of having multiple instances of the application using different resources. For example you might have an Apache web server on port 80 and a different one on port 81. Or perhaps more realistically a dev version of Tomcat (that can be killed if necessary) and a production version of Tomcat that is never killed - common resources can be used in both (I use this feature). Or you might have a dev database and a production database on the same physical machine, just on different ports and using different directory structures.