Is It Possible To Keep Nio In Op_write Mode Without High Cpu Usage
I have an Android app that acts as server and feeds over TCP some data from sensors with arbitrary intervals (within 5-60 seconds). Client apps occasionally send small chunks of da
Solution 1:
Your question and the samples you cite are based on a fallacy. There is no such thing as a 'mode' in NIO. You can read and write whenever you like, but they can both do nothing if done at the wrong time.
- OP_READ firing means that a read will return with data or end of stream, i.e. that there is data or a FIN in the socket receive buffer. This is normally false, except when the peer has sent some data or closed his end of the connection.
- OP_WRITE firing means that a write will transfer some data, i.e. that there is room in the socket send buffer. This is normally true, and this in turn is why selecting on it normally smokes the CPU.
- Normally a channel should only be registered for OP_READ.
- When you have something to write, write it.
- If and only if
write()
returns zero, register the channel for OP_WRITE, remember the buffer you were writing, and return to the select loop. - When OP_WRITE fires for this channel, repeat the write, and if it completes, deregister the channel for OP_WRITE.
There is a lot of junk on the Internet and this is particularly true where NIO is concerned. Among the numerous problems in your citation (seen over and over again in this kind of material):
select()
is not asynchronous;- 'only one of those can happen at a time' is false;
- you do not need the
Selector
's 'permission' to write; - registering OP_WRITE and waiting for it to fire when you have something to write and don't already know that the socket send buffer is full is just an elaborate and pointless waste of time;
- you can't change a channel that has been registered for OP_ACCEPT to read/write;
- closing a channel cancels the key;
- closing either the channel or the socket closes both;
finishConnect()
can return false;write()
can return zero, or less than the amount of data that was supplied;- OP_CONNECT can only fire if
isConnectionPending()
is true.
Post a Comment for "Is It Possible To Keep Nio In Op_write Mode Without High Cpu Usage"