Assuring there is only an instance of an application. "There Only Can be One!" (JAVA Code)

Assuring there is only an instance of an application.

 "There can be only one" (JAVA Code Version)


(HighLander Film 1986).

Note: It is important for you life to listen to this film's OST song: "Who Wants to Live Forever" (Queen 1986). But I am almost sure you know that song already, so keep on reading my article.


This is year 2013 and, as long as I know, Operating Systems do not give the facility for preventing an application to be launched twice. So it has to be done programmatically. Common ways of getting it done are:
  • Creating a file and blocking it so that the new process cannot get access to it. A funny use of a deadlock.
  • Opening a port and closing the new instance as soon as it checks that the port is already under use by another previous launched instance.
Both have advantages and disadvantages. This entry gives code for the second solution. Mind the firewall!

Now shut up and gimme tha codez:



package com.ramon.talavera.util;

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

/**
 * Determines if a port is being used by another application
 * Ramon Talavera 
 */
public class MultipleIntancesDetector {

    /**
     * Check if port is not used
     *
     * @param port
     * @return true if it is not used
     */
    public static boolean portIsNotUsed(int port) {
        try {
            Socket target_socket = new Socket("127.0.0.1", port);

            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * Launch the blocking port dummy server
     *
     * @param port
     */
    public static void launchBlockingPortSocketServer(int port) {
        if (portIsNotUsed(port)) {
            return;
        }

        MultipleInstancesBlockerServerSocket port_blocker = new MultipleInstancesBlockerServerSocket();
        port_blocker.setPort(port);
        port_blocker.start();
    }

    /**
     * Inner class , a dummy socket server that runs in its own thread.
     */
    public static class MultipleInstancesBlockerServerSocket extends Thread {

        private ServerSocket serverSocket = null;
        private Socket clientSocket = null;
        private int port;

        @Override
        public void run() {

            try {
                serverSocket = new ServerSocket(getPort(), 1);
                while (true) {
                    clientSocket = serverSocket.accept();
                    clientSocket.close();
                }
            } catch (Exception e) {
                System.out.println("MultipleInstancesBlockerServerSocket closed-");
            }

        }

        /**
         * Gets the Port
         *
         * @return the port
         */
        public int getPort() {
            return port;
        }

        /**
         * Sets the Port
         *
         * @param port the port to set
         */
        public void setPort(int port) {
            this.port = port;
        }
    }
  
}

Comments

Popular posts from this blog

Qt Signals and Slots, Connecting and Disconnecting

Vaadin 7: Detect Enter Key in a TextField

JAVA JPA WITH HIBERNATE AND H2 Tutorial