Question

I create AsynchronousServerSocketChannel and everything is fine untill I want close server socket socket. I create AsynchronousSocketChannel on client with special message which call function to close server and all socket channels, server is closed but finnally block is never executed why?

Check code:

 public void openServerSocket(int sport) {


    port = sport;
    policyFile = createPolicy(new String[]{"*:"+port});
    try {

        //group = AsynchronousChannelGroup.withThreadPool(Executors.newSingleThreadExecutor());
        //group.awaitTermination(1, TimeUnit.SECONDS);
        server = AsynchronousServerSocketChannel.open();
        server.bind(new InetSocketAddress(sport));


        server.accept(null, this);

       while(isOpen) {

            //System.out.println("running server socket");

        }
    }catch(Exception ex) {
        this.message = ex.getMessage();
        System.out.println("Server: " + ex.getMessage());
    }finally {

        System.out.println("Finall serversocket closing!");
        for(SocketHandler sh : sockets) {
            sh.close();
        }

        if(server != null) {
            try {
                server.close();
                server = null;
            }catch(Exception ex2) {
                this.message = ex2.getMessage();
            }
        }


        sockets.clear();
        sockets = null;
        //this.message = "server socket closed";

        System.out.println("server socket down");
    }

}

@Override
public void completed(AsynchronousSocketChannel socket, Void attachment) {

    System.out.println("new connection");
    SocketHandler sh = new SocketHandler(socket, this);

    server.accept(null, this);
}

@Override
public void failed(Throwable exc, Void attachment) {

    System.out.println("Server Failed accept:" + exc.getMessage());
}


public void closeServerSocket() {

    System.out.println("Closing server socket! " + server);
    this.isOpen = false;

}

So function closeServerSocket is called and I set false to variable isOpen which keep looping, but seems when I set false to isOpen var, while is still looping and finally is never executed?

Was it helpful?

Solution

This looks looks like an issue of communication between several threads. From the code I guess that your while(isOpen) loop runs in a different thread than the closeServerSocket() method of your class. To verify this add Thread.currentThread() to your print statements.

If this is the case, you can remedy the situation by declaring isOpen to be volatile. Without the volatile it is not guaranteed, if and when any other thread will see the written value. With the volatile it is guaranteed that (my interpretation of happens-before) a thread accessing the variable later (according to wall clock time) will see the changed value.

Instead of volatile you may prefer an AtomicBoolean.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top