Search code examples
javasocketsnio

Java NIO advantages if there is a single client and complete object read is required


Suppose the requirement for the TCP server that it is connected to a single client and it writes and reads serialized complete objects. The frequency of reading and writing is high. Given the requirement what are the advantages porting code from java IO to java NIO ?

Current code is something like this.. A dedicated thread for reading object from the socket and a dedicated thread for writing object to the socket. There is a single object input/output stream to which the objects is being written/read.

// Reading from socket 
private SomeObject readObject() throws IOException, ClassNotFoundException {
    Object object = oiStream.readObject();
    if (object != null && object instanceof SomeObject) {
        SomeObject someObject = (SomeObject) object;
        return someObject;
    }
    return null;
}

    // Writing to socket 
    public void writeToSocket(SomeObject someObject) throws IOException {
    if (isSocketOpen()) {
        ooStream.writeObject(someObject);
        ooStream.flush();
    } 
}

What would be NIO equivalent and its advantages given the fact that only one client will connect the server. Please do not discuss Channels/Selectors/Buffers instead compare the two library for a given requirement.


Solution

  • Object Serialization is so much more expensive than the difference between IO and NIO that you are unlikely to notice the difference. esp as Serialization is designed to work with IO.

    If you want to improve speed I suggest you try optimising the serialization.

    http://code.google.com/p/thrift-protobuf-compare/wiki/Benchmarking

    http://vanillajava.blogspot.com/2011/10/serialization-using-bytebuffer-and.html

    If serialization were not an issue you can transfer data faster with blocking NIO than blocking IO.

    http://vanillajava.blogspot.com/2010/07/java-nio-is-faster-than-java-io-for.html