Archive for juillet, 2005

Non-blocking I/O

« New I/O » is a feature appeared with jdk 1.4, implemented in package java.nio.channels.

This feature allows to define multiplexed Non-blocking I/O operations. Thus, on the server side, it’s not required to spawn a new thread each time a client connects. It’s the responsibility of the application to create a working thread.

Below, a simple example extracted from the NetCopyPaste program in start() method of org.florentgarin.netcopypaste.network.SocketListener class. It’s probably overkill but NetCopyPaste has been voluntarily written using all the latest technologies.

Selector selector = Selector.open();

//we only register read operation
_channel.register(selector, SelectionKey.OP_READ);

//selector.select() method blocks until a registered operation occurs.
//Thus, it's a infinite loop
while (selector.select() > 0 ) {

Set<SelectionKey> readyKeys = selector.selectedKeys();
Iterator<SelectionKey> iti = readyKeys.iterator();

while (iti.hasNext()) {

SelectionKey key = iti.next();
iti.remove();
if (key.isReadable()) {

//we can have created a thread to do the job but in our case
//there's not so much to do, so we have kept our code simple.
MessageEvent messageEvent = readMessage(key);
fireMessage(messageEvent);

}


}


}

Most application servers such as tomcat has been rewritten to take advantage of the nio packages. If your application has some performance or memory usage issues, you must consider refactoring your code.