Java network listeners

I’ve written a small listeners library today. It allows to create Callables which can be submitted to ExecutorService. The callable itself implements creating server socket and binding it to local port.

There two principal type of listeners: blocking and non-blocking (thanks to Java NIO.


Blocking listener is very simple but in can’t be interrupted by calling thread. So there’s no point in that:

Future<Socket> future = executor.submit( Listeners.createListener( PORT ) );
try {
    Socket socket = future.get( 1, TimeUnit.SECONDS );
} catch( TimeoutException e ) {
    future.cancel( true );
}

Listener will stay active and PORT will be bound still. The reason is in usage of the uninterruptible ServerSocket.accept().


In contrary non-blocking listener is more sophisticated but it can be interrupted by calling thread. So you can do that:

Future<Socket> future = executor.submit( Listeners.createListener( PORT ) );
try {
    Socket socket = future.get( 1, TimeUnit.SECONDS );
} catch( TimeoutException e ) {
    future.cancel( true );
}

Listener will be terminated and PORT will be freed.

Tags:
comments powered by Disqus