How to lock a process in java to prevent multiple instance at the same time

If you create a java program and run the jar file more than twice. You will see that same program is running two instance at the same time. There may be some events when you really dont want to see multiple instances of same program. You can prevent this in this easy way. The theory is to create a file using java and lock the file when program runs. If another instance is tried to execute it will try to access the same file. But it wont be able to that because the file is already openned and locked by another program (i.e another instance). Thus we will be able to exit the second instance showing a message that the program is already running.

Here the lock class that implements this feature.

package utils;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

/**
 *
 * @author Burhan Uddin
 */
public class lock {
    private static File f;
    private static FileChannel channel;
    private static FileLock lock;
    
    public lock()
    {
        try
        {
            f = new File("process.lock");
            // Check if the lock exist
            if (f.exists()) // if exist try to delete it
                f.delete();
            // Try to get the lock
            channel = new RandomAccessFile(f, "rw").getChannel();
            lock = channel.tryLock();
            if(lock == null)
            {
                // File is lock by other application
                channel.close();
                throw new RuntimeException("Two instance cant run at a time.");
            }
            // Add shutdown hook to release lock when application shutdown
            ShutdownHook shutdownHook = new ShutdownHook();
            Runtime.getRuntime().addShutdownHook(shutdownHook);
            
        }
        catch(IOException e)
        {
               throw new RuntimeException("Could not start process.", e);
        }
    }

    public static void unlockFile() {
        // release and delete file lock
        try
        {
            if(lock != null)
            {
                lock.release();
                channel.close();
                f.delete();
            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
 }

    static class ShutdownHook extends Thread {
        public void run() {
            unlockFile();
        }
    }
}

Here is sample main class that uses this lock class

package msngr;

import utils.lock;

/**
 *
 * @author Burhan Uddin
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        // try to lock the application for single instance run
        try
        {
            javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
            lock l = new lock();
        }
        catch(RuntimeException ex)
        {
            // exit main app
            javax.swing.JOptionPane.showMessageDialog(null, "This program is already running!");
            return;
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
        mainWindow mw = new mainWindow();
        sysTray st = new sysTray(mw);
        mw.setVisible(true);
    }

}

Related posts:

Tags: , , ,

To make money we lose our health, and then to restore our health we lose our money.... We live as if we are never going to die, and we die as if we never lived!

1 Comment Leave yours

  1. sergio #

    Hiya buddy,

    First thanks for sharing your knowledge.
    I tried you app and does not works because you do not have to delete the file if exist on lock constructor. If you remove it the app will work fine.

    Thanks a lot!

Leave a Reply