There is no such thing as perfect programming, but we shouldn’t be discouraged because programming is a constant pursuit of perfection.

  1. Overall model of NIO system

  2. (1) Use Buffer to Buffer data, and the Buffer can use the heap memory in addition to directly apply for the use of out-of-heap memory. What’s the difference between the two? With heap memory, there is a copying process, that is, if a read or write operation is to be performed, the data in the heap is copied to the direct memory before the operation is performed. Why do you do that? Because of the JVM heap garbage collector, if not copy to direct memory but in the heap to send commands to the operating system directly, in the process of the operating system to read and write, if the memory of the Java heap by the garbage collector recycling, the operating system can’t continue to read data from the memory or write data to the memory. If this chunk of memory data in the heap is first copied into direct memory, the operating system processes the data directly in direct memory, unaffected by the JVM garbage collector. Direct memory can be used for processing large objects for efficiency purposes, but to avoid overuse of direct memory, it is best to set the size of direct memory that can be used with the JVM parameter MaxDirectMemorySize. (2) Use Channel. Channel integrates IO and network transmission. It does not need to wait for the completion of the connection and the return result of business processing before it responds, but responds in real time. What’s the good of that? The benefit is non-blocking, which is the core role of NIO. After sending a request, the current thread without has been waiting to return the result to other operations, but can monitor whether have the result while dealing with other business, when there is a connection and results returned, handle, if no free time to do other things, and a thread can monitor multiple requests, and only in BIO has been waiting for a request. This allows a single thread to do what multiple threads can do in the BIO. (3) Selector is an optimization of the listening mechanism in a Channel. Normally, we use polling to listen to a request of a Channel, but Selector introduces an event listening mechanism, that is, after registering an event to be listened to, it will be notified if the event occurs. (4) Reactor thread model: Although NIO single thread can deal with many problems, it is difficult for a single thread to deal with a large number of business and high concurrency in production, so thread pool is introduced, and the request and business processing and other functions are simplified to make the efficiency higher and fault tolerance stronger. (5) Netty is the application of NIO Reactor thread model. Meanwhile, IT enhances NIO Channel and Buffer, and introduces the design mode of responsibility chain.