Java. Prevent the Jar App from multiple launches with a pop-up message "already running." (using ServerSocket ())

I am currently trying to display a pop-up message when a user tries to run the jar more than once. My current code is below

public static void main(String[] args){

  new ServerSocket(65535, 1, InetAddress.getLocalHost());// if there are already one 
                                                         // running jar, it will prevent 
                                                         // the program to execute

  JOptionPane.showMessageDialog(frame, "Hello World \n"); //Display hello world message 
                                                          // when run

}

expected output when user runs jar more than once:

Your jar application is already running . . .

My question is how can we display a message telling the user that the jar application is already running, because ServerSocket () will prevent the application from starting, so the message “already running” that I installed after that will not work.

ANSWER:

 try{
       new ServerSocket(65535, 1, InetAddress.getLocalHost());
       JOptionPane.showMessageDialog(frame, "Hello World \n");
    }
 catch(BindException ex){
        JOptionPane.showMessageDialog
             (frame, "Your jar application is already running . . . \n");
        System.exit(0);
    }
+4
source share
3 answers

BindException, " ", , catch.

IOExceptions, .

ServerSocket , , .

+1

- , , , , , , jvm

, eclipse .lock

+3

the best way is to create a file that displays the status of the program, and if the program is already running, do not let the program run again. but you have to be careful; if your program stops unexpectedly without an edit file before exiting, it creates problems when your program runs later

+2
source

Source: https://habr.com/ru/post/1533101/


All Articles