Java NIO usage and Principle Analysis (4) from the online data collation

Source: Internet
Author: User

Some of the details about the buffer are described in the previous article, and it is now finally possible to get into the most interesting parts of NiO that are non-blocking I/O. Typically, when synchronizing I/O operations, if the data is read, the code blocks until there is data available for reading. Similarly, the write call will block until the data can be written. The traditional server/client mode is based on TPR (thread per request), and the server establishes a thread for each client request, which is solely responsible for processing a customer request. One problem with this pattern is that the number of threads increases, and a large number of threads increase the cost of the server. Most implementations, in order to avoid this problem, have adopted a thread pool model and set the maximum number of thread pool threads, which brings new problems, if there are 200 threads in the thread pool, and 200 users are doing large file downloads, the No. 201 user's request will not be processed in time. Even if the No. 201 user only wants to request a page of a few KB size. The traditional server/client pattern is as follows:

NiO non-blocking I/O is based on the reactor mode of operation, I/O calls will not be blocked, instead of registering interested in specific I/O events, such as the arrival of readable data, new socket connections and so on, in the event of a particular incident, the system informs us. The core object of implementing nonblocking I/O in NiO is that Selector,selector is registering various I/O events, and when those events occur, it is the object that tells us what happened, as shown here:

As you can see, when any registered event such as read or write occurs, the corresponding Selectionkey can be obtained from the selector, and the event that occurs and the specific selectablechannel of the event can be found from the Selectionkey. To get the data that the client sent over. Refer to Java NIO usage and principle Analysis (i) for Selectablechannel

Using NiO non-blocking I/O to write server handlers can be broadly divided into the following three steps:

1. Register an event of interest to the selector object
2. Get events of interest from selector
3. According to the different events to deal with the corresponding

Next we use a simple example to illustrate the whole process. The first is to register an event of interest to the Selector object:

    /** Register Event **/      protectedSelector Getselector ()throwsIOException {//Create a Selector objectSelector sel =Selector.open (); //create selectable channels and configure as nonblocking modeServersocketchannel Server =Serversocketchannel.open (); Server.configureblocking (false); //bind channel to specified portServerSocket socket =Server.socket (); Inetsocketaddress Address=Newinetsocketaddress (port);                    Socket.bind (address); //registering an event of interest to the selectorserver.register (SEL, selectionkey.op_accept); returnsel; }  

The Serversocketchannel object is created and the Configureblocking () method is called, configured as nonblocking mode, the next three lines of code bind the channel to the specified port, and finally the event is registered to selector, where the parameter is specified as Op_ Accept, which specifies that we want to listen to the Accept event, which is the event generated when a new connection occurs, the only parameter we can specify for the Serversocketchannel channel is op_accept.

Get an event of interest from selector, that is, start listening and enter the inner loop:

/** Start listening **/    Public voidListen () {System.out.println ("Listen on" +port); Try {            while(true) {               //the call is blocked until at least one event occursSelector.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 pattern basically follows this approach. First call the Select () method, which blocks until at least one event occurs, and then uses the Selectedkeys () method to get the selectionkey of the event, and then uses the iterator to loop.

The final step is to write the corresponding processing code according to the different events:

/** Processing according to different events **/  protected voidProcess (Selectionkey key)throwsioexception{//receiving Requests    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 (); intCount =channel.read (buffer); if(Count > 0) {buffer.flip (); Charbuffer Charbuffer=decoder.decode (buffer); Name=charbuffer.tostring (); Selectionkey SKey=Channel.register (selector, selectionkey.op_write);           Skey.attach (name); } Else{channel.close ();       } buffer.clear (); }      //Write Events    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 judge whether to accept the request, read the data or write the event, and make different processing respectively.

Here are four articles on the use and principle analysis of Java NIO. Java NIO provides a set of abstractions, such as channels, buffers, selectors, which greatly simplifies the way we write high-performance, hair-styling server programs, with the opportunity to continue talking about some of the ideas behind using Java NiO.

Java NIO usage and Principle Analysis (4) from the online data collation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.