How to implement a Single Instance Application in Java
Recently I started processing command-line arguments in one of my Java Swing applications (Xadrian) so the application can load files directly on startup. This allows connecting the application with some mime-type or file extension and load files into the application by double-clicking the files. But unfortunately this isn't really usable because everytime a new instance of the application is launched by the operating system. So I searched for some technique to prevent this and found two articles: The first one explains how to use a lock file to prevent a second application instance while the second one explains how to use a local server socket to do the same.
The problem with the first solution is obvious: Even with a shutdown hook it is possible that the lock file is not removed properly (When JVM crashes for example). This prevents the application from being restarted. The user has to remove the lock file manually to be able to start the application again which is pretty annoying. The second solution doesn't have this problem because the server socket will be closed even when the JVM crashes. But this solution has a different problem: The port number must be fixed. And if there is already some other service using this port then this can cause a lot of confusion.
Both solutions have another problem: Just preventing the launch of a second instance isn't enough. When I double-click some data file and the operating system tries to open this file with a second instance of the application then I want the data file to be opened with the first instance instead. So the second instance must give the command line arguments to the first instance.
I haven't found a library which already does this so I had to write my own library.
Continue reading "How to implement a Single Instance Application in Java"