Monday, September 13, 2010

A few simple ways to break your blocking I/O operatio

Tranditional blocking I/O is not like Thread.sleep(), Object.wait(), Thread.join(), etc, it cannot interrupted by the Thread.interrupt() method, but the others list above could be interrupted and you will get InterruptedException.

In blocking I/O, such as ServerSocket.accept(), if no more connect requests coming, it will be blocked maybe for ever. If you create a listern listening on a port, but you want to shutdown it gracefully, you may choose the following ways to do that:

1. Create a client socket and call connect() to this listener's port:

        Socket client = new Socket();
        try {
            client.connect(new InetSocketAddress(this.IP, this.port));
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    This will make the ServerSocket.accept() break, and make the thread proceeds.

2. Keep a reference( i.e serverSocket) to the ServerSocket you created in the listener, later when you want to shutdown the listener, just call serverSocket.close(), this also break the ServerSocket.accept().

3. The third way is not so graceful, but if you don't care about what is runing, it works, just uses kill -9 to kill the process.

Posted via email from Progress

No comments:

Post a Comment