Java NIO and event processing model based on reactor design pattern

Source: Internet
Author: User

Java NiO non-clogging applications are commonly used in I/O reading and writing, we know that the performance bottleneck of the system operation is usually in I/O read and write, including Port and file operation, in the past, after opening an I/O channel, read () Will be waiting for the port to read the byte content, if there is no content to come in, read () is also silly and so on, which will affect our program to continue to do other things, then the improvement is to open a thread, let the thread to wait, but this is also very resource-intensive.

Java NiO non-clogging technology is actually to take the reactor mode, or observer mode for us to monitor the I/O port, if the content comes in, will automatically notify us , so that we do not have to open multiple threads death, from the outside, to achieve a smooth I/O Read and write , not clogged up.

Java NiO appears not just a technical performance improvement, you'll find it everywhere on the web, because it's a milestone, starting with JDK1.4, Java is starting to improve performance-related features, which makes Java in the bottom or parallel distributed computing and so on operation already can and C or Perl and other languages keep abreast.

If you still suspect Java performance, your ideas and ideas are completely out of date, Java should be defined in a year or two with new nouns. Starting with JDK1.5 and providing support for new features such as threading and concurrency, Java applications have matured in time-based areas such as gaming, and Java has been eating away from the traditional C domain after stabilizing its middleware position.

The Fundamentals of NiO:

NIO has a major class Selector, which resembles an observer, so long as we tell Selectorwhat we need to know, we go on to do something else, and when something happens, he informs us, Return a group of Selectionkey, we read these keys, we will get the socketchannel we just registered, then we read the data from this channel, rest assured that the package will be able to read, and then we can process the data.

Selector internal principle is actually doing a polling access to the registered channel, constantly polling (currently this algorithm), once polling to a channel to register things happen, such as the data came, he will stand up report, hand over a key, Let's use this key to read the channel's contents.

Use on:

We combine the code to see the use, in use, also in two directions, one is threading, one is non-threading, the latter is relatively simple, look at the following code:

Package Reactor.section3;import java.net.inetaddress;import java.net.inetsocketaddress;import java.net.Socket; Import Java.nio.channels.selectionkey;import Java.nio.channels.selector;import Java.nio.channels.serversocketchannel;import Java.nio.channels.socketchannel;import Java.util.Iterator;import Java.util.Set; Public classNBTest1 {Private Static voidPrintkeyinfo (Selectionkey SK) {String s=NewString (); S+="Att:"+ (sk.attachment () = =NULL?"No":"Yes"); S+=", Read:"+sk.isreadable (); S+=", ACPT:"+sk.isacceptable (); S+=", cnct:"+sk.isconnectable (); S+=", Wrt:"+sk.iswritable (); S+=", Valid:"+Sk.isvalid (); S+=", Ops:"+Sk.interestops ();    Debug (s); }    Private Static voidDebug (String s) {System. out. println (s); }     Public Static voidMain (String args[]) {NBTest1 nbtest=NewNBTest1 (); Try{nbtest.startserver (); } Catch(Exception e) {e.printstacktrace (); }    }            Private voidStartServer () throws exception{intChannels =0; intNkeys =0; intCurrentselector =0; //using selectorSelector Selector =Selector.open (); //establish channel and bind to port 9000Serversocketchannel SSC =Serversocketchannel.open (); Inetsocketaddress Address=NewInetsocketaddress (Inetaddress.getlocalhost (),9000);        Ssc.socket (). bind (address); //The way to set non-blocking. Ssc.configureblocking (false); //Register channel with selector and events of interest to USSelectionkey s =Ssc.register (selector, selectionkey.op_accept);        Printkeyinfo (s);  while(true)//Continuous Polling{Debug ("nbtest:starting Select"); //Selector notifies us by the Select method that the event we are interested in has occurred. Nkeys = Selector.Select(); //If something happens to our registration, it will return a value greater than 0 .            if(Nkeys >0) {Debug ("Nbtest:number of keys after select operation:"+Nkeys); Set Selectedkeys=Selector.selectedkeys (); Iterator I=Selectedkeys.iterator ();  while(I.hasnext ()) {s=(Selectionkey) i.next ();                    Printkeyinfo (s); Debug ("Nbtest:nr Keys in selector:"+Selector.keys (). Size ()); //once a key is processed, it is removed from the Ready keys listI.remove (); if(S.isacceptable ()) {//get the channel we just registered from the channel (). Socket socket =( (Serversocketchannel) S.channel ()). Accept (). socket (); Socketchannel SC=Socket.getchannel (); Sc.configureblocking (false); Sc.register (selector, Selectionkey.op_read|selectionkey.op_write); System. out. println (+ +channels); }Else{Debug ("Nbtest:channel Not acceptable"); }                }                                                            }Else{Debug ("Nbtest:select finished without any keys."); }        }            }}

This is an example of a noblock server waiting on port 9000, if we compile a client program, we can interact with it, or use telnet hostname 90000 to link to it.

The current distributed computing Web services are prevalent in the world, the bottom of these network service is inseparable from the operation of the socket. They all have a common structure:
1. Read Request
2. Decode Request
3. Process Service
4. Encode reply
5. Send Reply

Friends who have written to large and medium-sized Web servers believe that the event-handling model (sometimes called an event-triggering model) is unfamiliar. The reactor to be talked about today is a much more design pattern used in the event-handling model. Please look at the following figure, there is a preliminary impression:

In, you can see the following four main roles:

1. Reactor:
Reactor is the most critical role in reactor mode, which is the class in which the pattern ultimately provides the interface to the user. The user can register EventHandler (3) with reactor, and then reactor the "reaction (react)", and discovers that there is an event on the user's registered FD,

The user's event handler is recalled.

2. Synchrouseventdemultiplexer:

Synchrouseventdemultiplexer is also a more important role in reactor, it is reactor used to detect the user registration of FD on the event of a sharp weapon, through the reactor know what the FD on what kind of events, Then, on the basis of a number of distribution events, callback the user's event handler function.

3. EventHandler:
Eventhander is a tool for users to interact with reactor, and users can tell reactor what to do for me when a particular event occurs by registering their own EventHandler with reactor.

4. Concreteeventhandler:
Concreteeventhandler is a subclass of EventHandler, EventHandler is the base class used by reactor to specify interfaces, and the user's own event handlers must inherit from EventHandler.

"Java Reactor Code"

The Java NIO provides the basic mechanism for the implementation of the reactor pattern, and its selector informs us through Slectorkey when a channel has data, where we implement the binding of events and handler.

Reference: Java NiO http://www.jdon.com/concurrent/nio.pdf

Http://www.cnblogs.com/xuekyo/archive/2013/01/20/2868547.html

Java NIO and event processing model based on reactor design pattern

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.