简体   繁体   中英

Java: If I have a instance of my program running, how do I detect that, and then close the old one(s)

I only want one instance of my program running. But I want it to close the older ones, if they ore open.

This is in Java.

If the application is launched using Java Web Start it can access the SingleInstanceService of the JNLP API. Here is a demo. of the SIS .

You could always have a lock file, and make sure your program terminates if it can't acquire an exclusive lock on it.

Reference

I guess you're talking about a standalone java program, each instance running in its own JVM. In that case here are the options I see for you:

  • Set-up RMI calls between your programs (it looks a bit overkill)
  • Try cajo (I haven't tried it myself but it seems it could solve your problem)
  • If you're on unix/linux, invoke shell script to kill existing process
  • Use a home made solution, for example create a file with a unique name on the file system each time your program start and delete any other file present in the same directory. Then check periodically that the file attached to the current instance is still there (using a timer), if it's not, terminate the current JVM.

You can use a server socket address as an exclusive lock.

When your app starts, it will try to bind a server socket to a predefined address. If that fails, it means a previous instance of app is running and owning that address. Ping that address to tell the owner to exit.

serverSocket = new ServerSocket(localhost:8888)
if success, 
    start ServerSocketListeningThread
else
    socket = new Socket(localhost:8888)
    socket.close();
    sleep(100);
    repeat attempt of binding server socket

ServerSocketListeningThread
    serverSocket.accept();  //block until someone connects
    System.exit(); 

It's easy to shut down your app from command line

telnet localhost 8888

Just call the Exiter.isAlone() method in the main() method. It kills the previous.(It is an implementation of the solution of Irreputable, thank) A server socket is listening on the port 8181 (in this exemple). If it get any request, it exists and stop jvm (System.exist()). When u launch a new application, it try to install the socket listener. If it is ok, if the port is busy , it send a request to stop it. The method isAlone() is waiting the killing the previous is done. If u call it in the first line of the main(String[] s) method, u are sure the previous has been removed.

public class Exiter implements Runnable {

    private static final Exiter instance = new Exiter();
    private ServerSocket serverSocket;
    private int port = 8181;
    private boolean bStarting = true;

    private Exiter() {
        (new Thread(this)).start();
    }

    @Override
    public void run() {

        while (bStarting) {
            try {
                serverSocket = new ServerSocket(port);
                bStarting = false;
                awake();
            } catch (IOException e) {
                System.err.println("Exiter : "+e.getMessage()+"  port "+port);
                openSocketKillRequest();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
        }
        try {
            Socket s = serverSocket.accept();// Ca bloque
            System.err.println("Kimll Request from :" + s.getRemoteSocketAddress());
            System.exit(0);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    private void openSocketKillRequest() {
        try {
            System.err.println("Send request kill previous");
            Socket socket = new Socket("localhost", port);
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Exiter getInstance() {
        return instance;
    }

    private synchronized void awake(){
        notifyAll();
    }

    public synchronized boolean isAlone() {
        if(bStarting){
            try {
                wait();
            } catch (InterruptedException e) {

                e.printStackTrace();
            }
        }
        return true;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM