Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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.

like image 946
NullVoxPopuli Avatar asked Sep 15 '10 02:09

NullVoxPopuli


4 Answers

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.

like image 186
Andrew Thompson Avatar answered Nov 16 '22 17:11

Andrew Thompson


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

Reference

  • FileLock docs
like image 30
zigdon Avatar answered Nov 16 '22 15:11

zigdon


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.
like image 2
Damien Avatar answered Nov 16 '22 17:11

Damien


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
like image 1
irreputable Avatar answered Nov 16 '22 15:11

irreputable