0

When my Application, it bind on a given port when it started:

public boolean checkIsAlreadyStart() {
    try {
        final ServerSocket server = new ServerSocket();
        server.setReuseAddress(false);
        server.bind(new InetSocketAddress("127.0.0.1",APPLICATION_PORT ));
        if (server.isBound()){
            logger.debug("binding to port: {}", APPLICATION_PORT);
            return false;
        }
        return true;
    } catch (IOException e) {
        logger.error("cannot bind to port", e);
        return true;
    }
}

However, when i run two instance of the Application at the same time, the second instance can still run the method without the IOException. Do I have to call accept() method?

0

2 Answers 2

2

Cannot reproduce:

10/04/2013 3:55:34 PM S checkIsAlreadyStart
INFO: Bound to port: 9,999
10/04/2013 3:55:34 PM S checkIsAlreadyStart
SEVERE: cannot bind to port
java.net.BindException: Address already in use: JVM_Bind
    at java.net.PlainSocketImpl.socketBind(Native Method)
    at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:383)
    at java.net.ServerSocket.bind(ServerSocket.java:328)
    at java.net.ServerSocket.bind(ServerSocket.java:286)
    at S.checkIsAlreadyStart(S.java:33)
    at S.main(S.java:63)

However as server is a local variable it is likely to allow garbage-collection of the ServerSocket, which will close it. If your intention is to keep the port open you should make server an instance variable.

Sign up to request clarification or add additional context in comments.

Comments

0

Are you sure the first instance of the application is still running? You could place a Thread.sleep in the application to be sure it is still running when you launch the second instance.

I ran this twice and the second time failed, as you intended.

    public static void main(String args[]) {
    Menu m = new Menu();
    m.checkIsAlreadyStart();
    try {
    Thread.sleep(20000);
    } catch (Exception e){}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.