Monday, March 5, 2012

Java IO vs Java NIO

Well we all use Sockets in our daily lives, don't we?
All Java programmers writing mission critical applications for either client or server THIS IS FOR YOU!

Starting Java 1.4, Sun introduced a new API for I/O in Java, majority of Java geeks out there are unaware about it. The new API is called NIO or New I/O and offered new features as well as improved performance. According to Oracle's website on NIO, it has the following features:

  • Buffers for data of primitive types


  • Character-set encoders and decoders


  • A pattern-matching facility based on Perl-style regular expressions


  • Channels, a new primitive I/O abstraction


  • A file interface that supports locks and memory mapping


  • A multiplexed, non-blocking I/O facility for writing scalable servers

  • Packages include:

    • java.nio package: Buffers, which are used throughout the NIO APIs.
    • java.nio.channels package: Channels and selectors.
    • java.nio.charset package: Character encodings.
    • java.nio.channels.spi package: Service-provider classes for channels.
    • java.nio.charset.spi package: Service-provider classes for charsets.
    • java.util.regex package: Classes for matching character sequences against patterns specified by regular expressions.
    • java.lang.CharSequence interface: The interface implemented by objects that can be passed as arguments to methods in the java.util.regex package. The StringStringBuffer, andjava.nio.CharBuffer classes implement this interface.
    THE COOL PART:
    What's cool about NIO is it's optimization on specific I/O operation dealing with:
    • File
    • Network
    • Inter-process Communication
    At least 2 of these are needed almost daily by a programmer. The API adds a generic concept of Channel to the table meanwhile optimizing buffers using contiguous extent of memory along with features like paging  etc. It also emphasizes on "Pipes" (as in Unix Pipe) thereby allowing I/O more close to being native (please note pipe in Java can hook only 2 threads as source/sink i.e. in the same application; sorry not available for IPC yet). 
    I have not yet looked at the regex optimization in NIO (I hardly use regex :( , can't remember any of it). You can look up the regex stuff in NIO and if there is something interesting that you would like to share please comment below.

    No comments:

    Post a Comment