If you want to have only one instance of your Java program, you can refer to the following usage.
Original link: http://blog.csdn.net/yaerfeng/article/details/7264729
Java does not provide such a mechanism. From the operating system standpoint, a startup Java application is just a running instance of a JVM. Running two instances of the same application is just running two unrelated JVMs.
Only one instance can be guaranteed to run if there is an established communication mechanism between multiple running instances.
Scenario 1: Using the Java lock file mechanism, idea is fairly simple, allowing the running instance to obtain a mutex for a "well-known" file via Java.nio.channels.FileLock
ImportJava.io.*;Importjava.nio.channels.*; Public classOneinstance_1 { Public Static voidMain (string[] args)throwsException {filelock lck=NewFileOutputStream ("C:\\flagfile"). Getchannel (). Trylock (); if(Lck = =NULL) {System.out.println ("A Previous instance is already running ..."); System.exit (1); } System.out.println ("This is the first instance ..."); //Do some work here ..... }}
Issue: Platform-related
Scenario 2: Using Java.net.ServerSocket
ImportJava.io.*;Importjava.net.*; Public classoneinstance_2 {Private StaticServerSocket Listenersocket; Public Static voidMain (string[] args) {Try{Listenersocket=NewServerSocket (2004); //at the this point, no other sockets may listen on Port 2004.}Catch(java.net.BindException e) {System.err.println ("A Previous instance is already running ..."); System.exit (1); } Catch(FinalIOException e) {//An unexpected exception occurredSystem.exit (1); } //Do some work here ..... }}
Issue: Opening a service port may be affected by a firewall, and may conflict with other ports
Scenario 3: Using File.createnewfile () and File.deleteonexit ()
ImportJava.io.*; Public classOneinstance_3 { Public Static voidMain (string[] args)throwsException {File flagfile=NewFile ("C:\\flagfile"); if(false==Flagfile.createnewfile ()) {System.out.println ("A Previous instance is already running ..."); System.exit (1); } flagfile.deleteonexit (); System.out.println ("This is the first instance ..."); //Do some work here ..... }}
Source: · BBS Water-Wood Tsinghua Station smth.org [from:202.108.130.*]
Issue: The file may not be deleted for some reason, even if using Runtime.addshutdownhook () is likely to happen.
Java program only runs one instance [go]