Java NIO consist of the following core components:
- Channels
- Buffers
- Selectors
Java NIO have more classes and components than these, but the Channel, Buffer and Selector forms the core of the APIs, in my Opinion. The rest of the components, like Pipe and Filelock is merely utility classes to being used in conjunction with the three Cor E components. Therefore, I ' ll focus on these three-in-this NIO overview. The other components is explained in their own texts elsewhere in this tutorial. See the menu on the top corner of this page.
Channels and Buffers
Typically, all IO in NIO starts with a Channel. A Channel is a bit like a stream. From the Channel data can is read into a Buffer. Data can also is written from a Buffer into a Channel. Here is a illustration of that:
|
Java nio:channels read data into buffers, and buffers write data into Channels |
There is several Channel and Buffer types. Here are a list of the primary Channel implementations in Java NIO:
- FileChannel
- Datagramchannel
- Socketchannel
- Serversocketchannel
As can see, these channels cover UDP + TCP network io, and file IO.
There is a few interesting interfaces accompanying these classes too, but I'll keep them out of this Java NIO overview fo R simplicity ' s sake. They ' ll is explained where relevant, in and texts of this Java NIO tutorial.
Here are a list of the core Buffer implementations in Java NIO:
- Bytebuffer
- Charbuffer
- DoubleBuffer
- Floatbuffer
- Intbuffer
- Longbuffer
- Shortbuffer
These Buffer ' s cover the basic data types that you can send via Io:byte, short, int, long, float, double and characters.
Java NIO also has a mappedbytebuffer which are used in conjunction with memory mapped files. I ' ll leave this Buffer out of the This overview though.
Selectors
A Selector allows a single thread to handle multiple Channel ' s. This is handy if your application have many connections (Channels) open, but only have low traffic on each connection. For instance, in a chat server.
Here's an illustration of a thread using a Selector to handle 3 Channel ' s:
|
Java nio:a Thread uses A Selector to handle 3 Channel ' s |
To use a Selector you register the Channel's with it. Then you call it's Select () method. This method would block until there is a event ready for one of the registered channels. Once the method returns, the thread can then process these events. Examples of events is incoming connection, data received etc.
Java NIO Overview