Share this page 

Preventing multiple instances of an applicationTag(s): Varia


Because each application is running in it's own JVM, there is no obvious way to detect if a particuliar application is already running.

The socket technique
One way to detect to prevent multiple application execution is to use a simple socket server. The application will try a connection to that Server, if it's a success then the application is already running (and the application is stopped), if no connection is made then the application create the Server.

In this example, the simple server is running on the same machine as the application so the machine name is "localhost", the port 80 is used, you may want to customize the port number for your machine.

[JustOneServer.java]

import java.io.*;
import java.net.*;

public class JustOneServer extends Thread {
   // you may need to customize this for your machine
   public static final int PORT = 80 ; 

   ServerSocket serverSocket = null;
   Socket clientSocket = null;

   public void run() {
    try {
      // Create the server socket
      serverSocket = new ServerSocket(port, 1);
      while (true) {
       // Wait for a connection
       clientSocket = serverSocket.accept();
       // System.out.println("*** Got a connection! ");
       clientSocket.close();
       }
      }
    catch (IOException ioe) {
     System.out.println("Error in JustOneServer: " + ioe);
     }
    }
  }

[JustOne.java]

import java.io.*;
import java.net.*;

public class JustOne {
  SimpleDummyServer sds = null;  

  public static void main(String args[]){
    new JustOne().doit();
    }

 public void doit() {
    try {
      Socket clientSocket = new Socket("localhost", JustOneServer.PORT);
      System.out.println("*** Already running!");
      System.exit(1);
      }
    catch (Exception e) {
      sds = new JustOneServer();
      sds.start();
      }
    
    while(true) {
      try { System.out.print("."); Thread.sleep(5 * 60); }
      catch(Exception e) { e.printStackTrace(); }
      }
    }
 }
To test it out, open 2 consoles.

In console 1 , type java JustOne.

In console 2, type java JustOne and the application should response "Already running!".

The file lock technique
[JDK1.4+] You can use a flag file with a lock mechanism. The idea is to create and lock a file on user.home folder with a provided name. A concurrent execution will try to lock the same file and will failed. A special "shutdown hook" is provided to unlock the file when the JVM is shutting down.

[JustOneLock.java]

import java.io.*;
import java.nio.channels.*;

public class JustOneLock {
    private String appName;
    private File file;
    private FileChannel channel;
    private FileLock lock;

    public JustOneLock(String appName) {
        this.appName = appName;
    }

    public boolean isAppActive() {
        try {
            file = new File
                 (System.getProperty("user.home"), appName + ".tmp");
            channel = new RandomAccessFile(file, "rw").getChannel();

            try {
                lock = channel.tryLock();
            }
            catch (OverlappingFileLockException e) {
                // already locked
                closeLock();
                return true;
            }

            if (lock == null) {
                closeLock();
                return true;
            }

            Runtime.getRuntime().addShutdownHook(new Thread() {
                    // destroy the lock when the JVM is closing
                    public void run() {
                        closeLock();
                        deleteFile();
                    }
                });
            return false;
        }
        catch (Exception e) {
            closeLock();
            return true;
        }
    }

    private void closeLock() {
        try { lock.release();  }
        catch (Exception e) {  }
        try { channel.close(); }
        catch (Exception e) {  }
    }

    private void deleteFile() {
        try { file.delete(); }
        catch (Exception e) { }
    }
}

[JustOneTest.java]

public class JustOneTest {
    public static void main(String[] args) {
        new JustOneTest().test();
    }

    void test() {
        JustOneLock ua = new JustOneLock("JustOneId");

        if (ua.isAppActive()) {
            System.out.println("Already active.");
            System.exit(1);    
        }
        else {
            System.out.println("NOT already active.");
            try {
                while(true) {
                     try { System.out.print("."); Thread.sleep(5 * 60); }
                      catch(Exception e) { e.printStackTrace(); }
                }
             }
            catch (Exception e) {  }
        }
    }
}