How to implement a single instance Java application?

Viewed 66441

Sometime I see many application such as msn, windows media player etc that are single instance applications (when user executes while application is running a new application instance will not created).

In C#, I use Mutex class for this but I don't know how to do this in Java.

17 Answers

I use the following method in the main method. This is the simplest, most robust, and least intrusive method I have seen so I thought that I'd share it.

private static boolean lockInstance(final String lockFile) {
    try {
        final File file = new File(lockFile);
        final RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
        final FileLock fileLock = randomAccessFile.getChannel().tryLock();
        if (fileLock != null) {
            Runtime.getRuntime().addShutdownHook(new Thread() {
                public void run() {
                    try {
                        fileLock.release();
                        randomAccessFile.close();
                        file.delete();
                    } catch (Exception e) {
                        log.error("Unable to remove lock file: " + lockFile, e);
                    }
                }
            });
            return true;
        }
    } catch (Exception e) {
        log.error("Unable to create and/or lock file: " + lockFile, e);
    }
    return false;
}

If I believe this article, by :

having the first instance attempt to open a listening socket on the localhost interface. If it's able to open the socket, it is assumed that this is the first instance of the application to be launched. If not, the assumption is that an instance of this application is already running. The new instance must notify the existing instance that a launch was attempted, then exit. The existing instance takes over after receiving the notification and fires an event to the listener that handles the action.

Note: Ahe mentions in the comment that using InetAddress.getLocalHost() can be tricky:

  • it does not work as expected in DHCP-environment because address returned depends on whether the computer has network access.
    Solution was to open connection with InetAddress.getByAddress(new byte[] {127, 0, 0, 1});
    Probably related to bug 4435662.
  • I also found bug 4665037 which reports than Expected results of getLocalHost: return IP address of machine, vs. Actual results : return 127.0.0.1.

it is surprising to have getLocalHost return 127.0.0.1 on Linux but not on windows.


Or you may use ManagementFactory object. As explained here:

The getMonitoredVMs(int processPid) method receives as parameter the current application PID, and catch the application name that is called from command line, for example, the application was started from c:\java\app\test.jar path, then the value variable is "c:\\java\\app\\test.jar". This way, we will catch just application name on the line 17 of the code below.
After that, we search JVM for another process with the same name, if we found it and the application PID is different, it means that is the second application instance.

JNLP offers also a SingleInstanceListener

We use file locking for this (grab an exclusive lock on a magic file in the user's app data directory), but we are primarily interested in preventing multiple instances from ever running.

If you are trying to have the second instance pass command line args, etc... to the first instance, then using a socket connection on localhost will be killing two birds with one stone. General algorithm:

  • On launch, try to open listener on port XXXX on localhost
  • if fail, open a writer to that port on localhost and send the command line args, then shutdown
  • otherwise, listen on port XXXXX on localhost. When receive command line args, process them as if the app was launched with that command line.

I wrote a dedicated library for that https://sanyarnd.github.io/applocker

It is based on file-channel locking, so it will not block a port number, or deadlock application in case of power outage (channel is released once process is terminated).

Library is lightweight itself and has a fluent API.

It was inspired by http://www.sauronsoftware.it/projects/junique/, but it's based on file channels instead. And there are other extra new features.

You can open a Memory Mapped File and then see if that file is OPEN already. if it is already open, you can return from main.

Other ways is to use lock files(standard unix practice). One more way is to put something into the clipboard when main starts after checking if something is already in the clipboard.

Else, you can open a socket in a listen mode(ServerSocket). First try to connect to hte socket ; if you cannot connect, then open a serversocket. if you connect, then you know that another instance is already running.

So, pretty much any system resource can be used for knowing that an app is running.

BR, ~A

You could try using the Preferences API. It is platform independent.

I used sockets for that and depending if the application is on the client side or server side the behavior is a bit different:

  • client side : if an instance already exists(I cannot listen on a specific port) I will pass the application parameters and exit(you may want to perform some actions in the previous instance) if not I will start the application.
  • server side : if an instance already exists I will print a message and exit, if not I will start the application.

The Unique4j library can be used for running a single instance of a Java application and pass messages. You can see it at https://github.com/prat-man/unique4j. It supports Java 1.6+.

It uses a combination of file locks and dynamic port locks to detect and communicate between instances with the primary goal of allowing only one instance to run.

Following is a simple example of the same:

import tk.pratanumandal.unique4j.Unique4j;
import tk.pratanumandal.unique4j.exception.Unique4jException;

public class Unique4jDemo {

    // unique application ID
    public static String APP_ID = "tk.pratanumandal.unique4j-mlsdvo-20191511-#j.6";

    public static void main(String[] args) throws Unique4jException, InterruptedException {

        // create unique instance
        Unique4j unique = new Unique4j(APP_ID) {
            @Override
            public void receiveMessage(String message) {
                // display received message from subsequent instance
                System.out.println(message);
            }

            @Override
            public String sendMessage() {
                // send message to first instance
                return "Hello World!";
            }
        };

        // try to obtain lock
        boolean lockFlag = unique.acquireLock();

        // sleep the main thread for 30 seconds to simulate long running tasks
        Thread.sleep(30000);

        // try to free the lock before exiting program
        boolean lockFreeFlag = unique.freeLock();

    }

}

Disclaimer: I created and maintain Unique4j library.

Related