oz1cz oz1cz - 14 days ago 4
Java Question

Implement a Single Instance Java Application

I'm not sure if the is a Windows or a Java question.

I have a Java application running under Windows. I have associated a particular file extension (say, .xyz) with my application, so that when I double click a .xyz file, my Java application is started and the main() method sees the .xyz file as its first argument.

But when I click another .xyz file, a new instance of the Java application is launched. I would prefer the existing application to handle the new file.

Is there a standard way to do this, or do I need to program it from scratch?

If the latter is the case, I presume I have to do something like this: When the second instance of the application is launched, it checks if another instance is already running (how?), opens a communication link to that first instance, and passes the name of the file. Right?

Answer

Here's one approach:

When your main() fires, it first opens a particular port and listens for other (subsequent) open-file actions.

If the port is already open, it means there's another instance running, so open a socket to the already-running instance's listening port and hand it enough information to complete processing then exit.