Java NIO Overview
Java NIO consist of the following core components:
- Channels
- Buffers
- Selectors
Java NIO have more classes and components than these, but Channel
the, and forms the core of the Buffer
Selector
APIs, in my Opini On. The rest of the components, like and is Pipe
FileLock
merely utility classes to being used in conjunction with the three core 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 is Channel
a bit like a stream. From the Channel
data can is read into a Buffer
. Data can also is written from A to Buffer
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 so 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 out of the this Buffer
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.
Illustration of a thread using a to Selector
handle 3 Channel
' s:
|
Java nio:a Thread uses A Selector to handle 3 Channel ' s |
To use a You Selector
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 (1) Overview