Java - Single instance of application - working source code example

Having a single instance of an application is crucial in most of the software. In this article, I am giving an example on how to implement single instance of  an Application.
How it works :
  1. New instance of application tries to connect to a specific ServerSocket (localhost, port#) to detect running applications. And a running application must have a ServerThread to detect possible run of new instance of the same application
  2. The main Logic in steps
    • Find existing server socket running on localhost
    • If found(another instance was already running) --> exit current instance of application
    • else --
      •  start a new Server thread to detect run of future applications
      •  and start the application
Complete source code :

import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class AppStarter {
    private String HOST = "localhost";
    private int PORT = 2222;

    public static void main(String[] args) {
        new AppStarter();
    }

    public AppStarter() {

        // try to connect to server
        if (findExisting()) {
            JOptionPane.showMessageDialog(null, "Another instance of this program\nis already running\nClick OK to Quit...");
            System.exit(0);
        }

        // start detecting server thread
        new Thread(new DetectForNew()).start();

        // start app instance
        new MyApp();

    }

    private boolean findExisting() {
        Socket client;
        try {
            System.out.println("creating socket");
            client = new Socket(HOST, PORT);
            System.out.println("Connection accepted by already running app");
            return true;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            System.out.println("Not Found - Not running");
            return false;
        }
    }

    class DetectForNew implements Runnable {
        ServerSocket serverSocket;

        @Override
        public void run() {
            System.out.println("detect thread started");
            try {
                serverSocket = new ServerSocket(PORT);
                while (true) {
                    serverSocket.accept();
                    System.out.println("multiple run attempt detected");
                }
            } catch (Exception e) {
                System.out.println("detect thread terminated ");
                e.printStackTrace();
            }
        }
    }

}

//Application Class - GUI
class MyApp extends JFrame {
 public MyApp() {
  setSize(200, 300);
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  setVisible(true);
 }
}


Try to  run two instances of this program. and see what happens. :D

No comments :

Post a Comment

Your Comment and Question will help to make this blog better...