When using the IO method of the socket provided by Java, the server creates a new thread for each connection, and one thread handles the data interaction of one client for convenience.
However, when a large number of clients are connected to the server, a large number of threads are created, and the switching between threads can severely affect the performance of the server, and sometimes each thread is not long or even short-lived.
The root cause of performance on the server side is the excessive number of threads.
To work around this problem, you can use the thread pool method. However, using the thread pool, which is still a thread processing a connection, and the size of the thread limits the number of simultaneous connections, can still improve performance, so use the NIO method to handle multiple connections through one thread, reducing the time-consuming and performance of thread switching.
Because multiple connections are processed through one thread, the use of native IO will be different.
There are several new classes to note: Channel,selector,buffer.
The channel represents an IO operation instance, and each selector creates a new thread that simply registers the channel and the changes it needs to notify to selector, and can iterate through the selector state. Know which channel has the corresponding IO changes, thus further operating the channel.
If the non-blocking channel is used, all IO data is saved from the source stream to the buffer instance, so the operation location of the data is also changed, from InputStream and outputstream to buffer.
With NiO, a lot of short-time concurrent IO performance is improved.
Understanding of JAVA NiO