Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

mutex - How to make sure that only a single instance of a Java application is running?

I want my application to check if another version of itself is already running.

For example, demo.jar started, user clicks to run it again, but the second instance realizes "oh wait, there is already a demo.jar running." and quits with a message.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Enforce one instance of a program running with a ServerSocket Lock

Java Code. Put this into a file called Main.java:

import java.net.*;
import java.io.*;
public class Main{
  public static void main(String args[]){
    ServerSocket socket = null;
    try {
      socket = new ServerSocket(34567);
      System.out.println("Doing hard work for 100 seconds");
      try{ Thread.sleep(100000); } catch(Exception e){ }
      socket.close();
    }
    catch (IOException ex) {
      System.out.println("App already running, exiting...");
    }
    finally {
      if (socket != null)
          try{ socket.close(); } catch(Exception e){}
    }
  }
}

Compile and run it

javac Main.java
java Main

Test it in a normal case:

Run the program. You have 100 seconds to run the program again in another terminal, it will fall through saying its already running. Then wait 100 seconds, it should allow you to run it in the 2nd terminal.

Test it after force halting the program with a kill -9

  1. Start the program in terminal 1.
  2. kill -9 that process from another terminal within 100 seconds.
  3. Run the program again, it is allowed to run.

Conclusion:

The socket occupation is cleaned up by the operating system when your program is no longer operating. So you can be sure that the program will not run twice.

Drawbacks

If some sneaky person, or some naughty process were to bind all of the ports, or just your port, then your program will not run because it thinks its already running.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...