Implementation method of JAVA program Single instance running __java

Source: Internet
Author: User
Requirements:

Recently done a Java project, after the completion of the package installed, found that you can point to more than one instance, because the desktop display tray, so the point will appear a tray, and the system also has several JAVAW process, so the words can not guarantee the robustness of the program, So you need to make a judgment that the program runs only one instance.
Implementation mode: Java does not provide such a mechanism. From an operating system standpoint, a startup Java application is just a running instance of a JVM. Run two instances of the same application, running only two unrelated JVMs.
Only one instance can be guaranteed to run only if there is an established communication mechanism between multiple running instances.
Because platform-independent, instance control of Java programs should not be done using the kernel objects of the system, we must find other resources that can be used alone. In fact, a machine, no matter what operating system it is on, network ports are exclusive, that is, based on the principle of network port, we can easily let our Java program implementation in memory only a running instance of this function, and the implementation of this function is not platform-independent.
Using the port number control method, create the port first, and then determine if the port is occupied to determine whether to start a new instance. The way the file locks are used is to lock the file when the program is run, and then determine if the file is locked to determine whether to run a new instance. Using the port number + file method, the use of this method is to create a file at startup, delete the file when it is closed, of course, only such an operation can not play the above requirements, if the illegal shutdown, the file still exists can not meet the requirements, can only be coupled with a port control, That is, when the port is occupied and the file exists, stop running the new instance, or start an instance, which can be satisfied by experiment.


Code implementation: The first implementation: Port control

Scenario: Using the Java.net.ServerSocket//problem: Opening a service port may be affected by a firewall and may conflict with another port.
Import java.io.*;
Import java.net.*; public class Oneinstance_2 {    private static serversocket listenersocket;     Public STA tic void Main (string[] args)     {        try          {            Listenersocket = new
ServerSocket (2004);            //at This point, no other socket may listen on port 20        }         catch ( Java.net.BindException e)         {       
     System.err.println ("A Previous instance is already running ...");
            system.exit (1);        }         catch (Final IOException e)      An unexpected exception occurred         {      
      system.exit (1);
       }        /do some work ...
    }}
Second implementation: file Locks

/* scenario: Using the Java lock file mechanism, idea is fairly simple, allowing the runtime to obtain a "well-known" file mutex by Java.nio.channels.FileLock.
*///existing problem: platform-related import java.io.*;
import java.nio.channels.*; public class oneinstance_1 {  public static void main (String[]  args)  throws exception {    FileLock lck = new 
FileOutputStream ("C:\\flagfile"). Getchannel (). Trylock ();              if (lck == null)  {      system.out.println
("a previous instance is already running ...");
      system.exit (1);    &NBSP}     system.out.println ("this is the first 
Instance of this program ... ");     // do some work here ...   }} 

Scenario 3: Use File.createnewfile () and File.deleteonexit ()///problem: Files may not be deleted for some reason, even with Runtime.addshutdownhook ().
Import java.io.*;  public class Oneinstance_3 {    public static void Main (string[] args) throws Exception     {        File Flagfile = new file ("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" instance.);  &
 nbsp; //Do some work ...    }

The Third Way: Port + file lock

public static void Main (string[] args) throws IOException {///create Lock.java file String filePath = new File ("Idrcalld

    ll "). GetAbsolutePath (). substring (0, New File (" Idrcalldll "). GetAbsolutePath (). LastIndexOf (" \ "));

    File GetFile = new file (FilePath + "\" + "Lock.java");

    System.out.println (Getfile.getpath ());

    Determine if the port is occupied boolean flag = Islocleportusing (20520);

    SYSTEM.OUT.PRINTLN (flag);

        If the file exists and the port is occupied, exit if (getfile.exists () && flag) {new Mytray (). ShowDialog ();

    System.exit (0); try {Socket sock = new socket ("127.0.0.1", 20520);//Create Socket, connect 20520 port} catch (Exception E {SYSTEM.OUT.PRINTLN ("port is occupied.)

    ");

    Final class<?> clazz = (class<?>) javacall.class;

    Final Boolean iswindows = System.getproperty ("Os.name"). Contains ("Windows");

Final list<string> args1 = new arraylist<string> ();    Args1.add (iswindows?)

    "JAVAW": "Java");

    Args1.add ("-xmx" + 128 + "M");

    Args1.add ("-CP");

    Args1.add (System.getproperty ("Java.class.path"));

    Args1.add ("-djava.library.path=" + system.getproperty ("Java.library.path"));

    Args1.add (Clazz.getcanonicalname ());

    Logger.info ("Start" + args1.tostring ());

    Final Processbuilder PB = new Processbuilder (ARGS1);



    Pb.redirecterrorstream (TRUE);

    try {/** * Read ID card information procedure * * Pb.start ();

    catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();

    Randomaccessfile r = new Randomaccessfile (FilePath + "\" + "Lock.java", "RWS");

    FileChannel temp = R.getchannel ();

Filelock fl = Temp.lock (); /** * Determine if the port is occupied * @param ports * @return/public static Boolean islocleportusing (int port) {Boolean flag =

    True try {flag = isportusing ("127.0.0.1", PorT);

catch (Exception e) {} return flag;

    public static Boolean isportusing (String host, int port) throws Unknownhostexception {Boolean flag = false;

    InetAddress theaddress = inetaddress.getbyname (host);

    System.out.println (theaddress);

        try {serversocket socket = new ServerSocket (port);

    Flag = true;

    catch (IOException e) {System.out.println ("Beizhanyong");

return flag; }

Resources:

Let the Java program run only one instance

How do I get a Java program to run only one instance


Concluding remarks **************************** ****************************************************************
I am writing this blog is also a beginner, have any questions or questions please leave a message, or send an email can also, the mailbox is: 577328725@qq.com, I will make corrections and changes as soon as possible.
In the blog I wrote two blog is the collation of resources, may be helpful to everyone, you can see if you are interested.
Download Data Collation-directory: http://blog.csdn.net/fanxiaobin577328725/article/details/51894331
This blog inside is my I see the feeling good good resource collation, which contains books and source code as well as personal search of some resources, if interested can see, I will always update and add.
Excellent article & Excellent Learning website Collection Manual: http://blog.csdn.net/fanxiaobin577328725/article/details/52753638
This blog is what I have read, and feel the meaning of the collection of articles, pure personal interests, people feel interested can read, I will often update it.
Thank ***************************** ***************************************************************

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.