In the previous article, I introduced some details about the Buffer Zone. Now I/O is the most interesting part of NiO. Generally, when synchronizing I/O operations, if the data is read, the code will block until there is data available for reading. Similarly, the write call will be blocked until data can be written. The traditional server/client mode is based on TPR (thread per request). The server creates a thread for each client request, which is responsible for processing a client request separately. A problem caused by this mode is the increase in the number of threads, and a large number of threads will increase the overhead of the server. To avoid this problem, most implementations adopt the thread pool model and set the maximum number of threads in the thread pool. This introduces a new problem. If there are 200 threads in the thread pool, however, if 200 users download large files, the requests of 201st users cannot be processed in a timely manner, even if 201st users only want to request a page of several kb. Shows the traditional server/client mode:
NIO's non-blocking I/O adopts the reactor-based mode, and I/O calls are not blocked. On the contrary, it registers specific I/O events of interest, such as the arrival of readable data, new socket connections, etc. The system will notify us when a specific event occurs. The core object for implementing non-blocking I/O in NIO is selector, and Selector is the place where various I/O events are registered, and when those events occur, this object tells us what happened, as shown in:
It can be seen that when any registered event such as read or write occurs, the corresponding selectionkey can be obtained from the selector, you can also find the event and the specific selectablechannel of the event from the selectionkey to obtain the data sent by the client. For details about selectablechannel, refer to the usage and Principle Analysis of Java NiO (1)
Using NiO to write non-blocking I/O server processing programs can be divided into the following three steps:
1. register events of interest with the selector object
2. Get events of interest from Selector
3. Handle different events accordingly
Next we will use a simple example to illustrate the entire process. First, register an event of interest to the selector object:
[Java]View plaincopyprint?
- /*
- * Register an event
- **/
- Protected selector getselector () throws ioexception {
- // Create a selector object
- Selector sel = selector. open ();
- // Create a selectable channel and configure the non-blocking mode
- Serversocketchannel Server = serversocketchannel. open ();
- Server. configureblocking (false );
- // Bind the channel to the specified port
- Serversocket socket = server. socket ();
- Inetsocketaddress address = new inetsocketaddress (port );
- Socket. BIND (Address );
- // Register an event of interest with Selector
- Server. Register (SEL, selectionkey. op_accept );
- Return sel;
- }
Create a serversocketchannel object and call the configureblocking () method to configure the non-blocking mode. The next three lines of code bind the channel to the specified port, and finally register the event to the selector, the parameter op_accept is specified here, that is, the event generated when a new connection is generated. For the serversocketchannel, the only parameter that can be specified is op_accept.
Get the event of interest from selector, that is, start listening, and enter the internal loop:
[Java]View plaincopyprint?
- /*
- * Start listening
- **/
- Public void listen (){
- System. Out. println ("listen on" + port );
- Try {
- While (true ){
- // The call will be blocked until at least one event occurs.
- Selector. Select ();
- Set <selectionkey> keys = selector. selectedkeys ();
- Iterator <selectionkey> iter = keys. iterator ();
- While (ITER. hasnext ()){
- Selectionkey key = (selectionkey) ITER. Next ();
- ITER. Remove ();
- Process (key );
- }
- }
- } Catch (ioexception e ){
- E. printstacktrace ();
- }
- }
In non-blocking I/O, the internal loop mode basically follows this method. First, call the select () method. This method will be blocked until at least one event occurs. Then, use the selectedkeys () method to obtain the selectionkey of the event, and then use the iterator for loop.
The last step is to write the corresponding processing code based on different events:
[Java]View plaincopyprint?
- /*
- * Handle different events
- **/
- Protected void process (selectionkey key) throws ioexception {
- // Receives the request
- If (key. isacceptable ()){
- Serversocketchannel Server = (serversocketchannel) Key. Channel ();
- Socketchannel channel = server. Accept ();
- Channel. configureblocking (false );
- Channel. Register (selector, selectionkey. op_read );
- }
- // Read information
- Else if (key. isreadable ()){
- Socketchannel channel = (socketchannel) Key. Channel ();
- Int COUNT = channel. Read (buffer );
- If (count> 0 ){
- Buffer. Flip ();
- Charbuffer = decoder. Decode (buffer );
- Name = charbuffer. tostring ();
- Selectionkey skey = channel. Register (selector, selectionkey. op_write );
- Skey. Attach (name );
- } Else {
- Channel. Close ();
- }
- Buffer. Clear ();
- }
- // Write event
- Else if (key. iswritable ()){
- Socketchannel channel = (socketchannel) Key. Channel ();
- String name = (string) Key. Attachment ();
- Bytebuffer block = encoder. encode (charbuffer. Wrap ("hello" + name ));
- If (block! = NULL)
- {
- Channel. Write (Block );
- }
- Else
- {
- Channel. Close ();
- }
- }
- }
Here, we determine whether to accept requests, read data, or write events, and perform different processing respectively.
The four articles on the usage and Principle Analysis of Java NiO have been completed. Java NiO provides a set of abstract concepts such as channel, buffer, and selector, which greatly simplifies the compilation of high-performance and hairstyle server programs. I will continue to talk about some ideas about using Java NiO later.
(End)