The implementation of a NiO is different. The following is a simple example:
Java code
- Bytebuffer buffer = bytebuffer. Allocate (48 );
- Int bytesread = inchannel. Read (buffer );
Note that the second row reads bytes from the channel to bytebuffer. When this method is returned, you do not know whether all the data you need is in the buffer zone. What you know is that the buffer contains some bytes, which makes processing a little difficult.
The bufferfull () method must track how much data is read into the buffer and return true or false, depending on whether the buffer is full. In other words, if the buffer is ready for processing, it indicates that the buffer is full.
The bufferfull () method scans the buffer, but the status must be the same before the bufferfull () method is called. If no, the data read from the next buffer may not be able to read the correct location. This is not possible, but it is another issue that requires attention.
Summary
NIO allows you to manage multiple channels (network connections or files) with only one (or several) single thread ), however, the price is that parsing data may be more complex than reading data from a blocked stream.
If you need to manage thousands of connections opened at the same time, these connections only send a small amount of data each time, such as chat servers, the server implementing NiO may be an advantage.
Channel implementation
These are the most important channel implementations in Java Nio:
- Filechannel: read and write data from a file.
- Datagramchannel: reads and writes data in the network through UDP.
- Socketchannel: reads and writes data in the network over TCP.
- Serversocketchannel: It can listen to new TCP connections, just like the web server. A socketchannel is created for each new connection.
What is non-blocking io?