Java NIO vs IO


As we know that java NIO is introduced for advancement of conventional java IO API.The main enhancements which make NIO more efficient than IO are channel data flow model used in NIO and use of operating system for conventional IO tasks.

The difference between Java NIO and Java IO can be explained as following −

  • As mentioned in previous post in NIO buffer and channel oriented data flow for I/O operations which provide faster execution and better performance as compare to IO.Also NIO uses operating system for conventional I/O tasks which again makes it more efficient.

  • Other aspect of difference between NIO and IO is this IO uses stream line data flow i.e one more byte at a time and relies on converting data objects into bytes and vice-e-versa while NIO deals with the data blocks which are chunks of bytes.

  • In java IO stream objects are unidirectional while in NIO channels are bidirectional meaning a channel can be used for both reading and writing data.

  • The streamline data flow in IO does not allow move forth and back in the data.If case need to move forth and back in the data read from a stream need to cache it in a buffer first.While in case of NIO we uses buffer oriented which allows to access data back and forth without need of caching.

  • NIO API also supports multi threading so that data can be read and written asynchronously in such as a way that while performing IO operations current thread is not blocked.This again make it more efficient than conventional java IO API.

  • Concept of multi threading is introduced with the introduction of Selectors in java NIO which allow to listen to multiple channels for IO events in asynchronous or non blocking way.

  • Multi threading in NIO make it Non blocking which means that thread is requested to read or write only when data is available otherwise thread can be used in other task for mean time.But this is not possible in case of conventional java IO as no multi threading is supported in it which make it as Blocking.

  • NIO allows to manage multiple channels using only a single thread,but the cost is that parsing the data might be somewhat more complicated than when reading data from a blocking stream in case of java IO.So in case fewer connections with very high bandwidth are required with sending a lot of data at a time,than in this case java IO API might be the best fit.