Georgian Citizen
Georgian Citizen

Reputation: 4027

how can i avoid running of more than one instance on same java project at the same time?

i have a java project, works as a server. when an instance of this project running, i can run another instance.
how can i avoid running of more than one instance on same java project at the same time? (Stop the server when another instance is detected)

Upvotes: 1

Views: 759

Answers (4)

user597987
user597987

Reputation:

import java.net.ServerSocket; 
..... 
private static final int PORT = 9999;
private static ServerSocket socket;  
public static void main(String[] args) {

    try {
        socket = new ServerSocket(PORT, 0, InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }));

                {/*here write your own code taht must be run in the main*/}

    } catch (BindException e) {
        System.err.println("**********************************Already running.");
        System.exit(1);
    } catch (IOException e) {
        System.err.println("************************************Unexpected error.");
        e.printStackTrace();
        System.exit(2);
    } catch (Exception e) {
        System.err.println("************************************ Error");
        System.exit(3);
    }
}

i used this code and it work try it

Upvotes: 3

mazaneicha
mazaneicha

Reputation: 9425

I totally support @vickirk - his approach allows the second "un-needed" instance of your server become "dormant" instead of simply terminating, i.e. periodically run to perform a check if the "active" instance is still actually active/present, and take over if it went down.

In the distrubuted case, if the requirement is to have a single server instance spanning multiple machines, the approach is still to find a common resource that can be locked, physically or logically. For that purpose, I personally use a control database table where an active process writes its PID and "heartbeat", and all others are checking for that "heartbeat" to be fairly recent, and become active if its not.

Upvotes: 1

Dmytro
Dmytro

Reputation: 195

you can write simple command line script for app start - that check is server runs before actually run new instance. Just check url with wget for example...

Upvotes: 0

vickirk
vickirk

Reputation: 4067

Easiest way is to use lock file, this causes problems if the app crashed. Try writing the pid into the lock file, you can check if that pid exists (although not natively maybe in a wrapper shell script).

If you are running server can you not check if a port is open, or better still maybe a jmx instance on a known port.

Upvotes: 2

Related Questions