Introduce
NIO
is make up for IO
‘s lack
NIO have some new characters:
no block i/o, selector, buffer and channelChannel
Buffer
Selector
is the main force.
Channel
like Stream in traditional style java.Buffer
1
2
3
4
5
6
7ByteBuffer byte
CharBuffer char
ShortBuffer short
IntBuffer int
LongBuffer long
FloatBuffer float
DoubleBuffer doubleSelector
Used to listen mulity channel’s event.
In traditional tyle when i/o unblock, we know we can i/o.
But use NIO, we need this equipment to manage i/o.
The difference
- IO is design for stream, NIO is design for block.
IO stream operate a byte every time, it lead to low efficiency.
NIO operate a type of data block, it’s bigger than a byte[maybe].
- IO is block, NIO is unblock
Traditional IO when a thread callread()
orwrite()
,
thread need to waiting for data operation finished.
During this time thread will be hang on? nothing it can be done.
To NIO when a thread send a request, but no response.
It’s a free, it can do any other tasks, until selector call.
Scene
NIO’s disadvantage is it need to check buffer space everytime.
Because it design for block, if block is not completed,
there is no meaning to operate data.
NIO fit for thousands short link and little data.
IO fit for few long link and big data.
Explain
Three guys got a task, to drink 50L water.
They all got a 100ml break. Have three water taps, it has no valve,
occasionally 100ml water flow out.
So these three poor guys have to wait until drink 500 cup of break.
Fantasy
But if they have a plumber to manage these water tap, thing wil be big different.
- First he can prepare three big bucket maybe 1L capacity each.
- Second he can install a valve in each tap.
- Third every guy told plumber their phone number,
when bucket filled with water, plumber call them to come, and close valve.
Use this mechanism guy need to come and drink 5 times bucket.
Thinking
If the water tap’s water flow is very strong,
then this mechanism is not good.
Because plumber’s manage tap needs time, and it’s buckets needs space.
So in this condition, these guys waiting for break
be filled with water and drink is a better chooice.