Java NIO usage and principle Analysis (d) (EXT)

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:

[Java]View PlainCopyprint?
  1. /*
  2. * Register Event
  3. * */
  4. Protected Selector Getselector () throws IOException {
  5. //Create selector object
  6. Selector sel = Selector.open ();
  7. //Create selectable channels and configure as nonblocking mode
  8. Serversocketchannel Server = Serversocketchannel.open ();
  9. Server.configureblocking (false);
  10. //BIND channel to specified port
  11. ServerSocket socket = Server.socket ();
  12. Inetsocketaddress address = new inetsocketaddress (port);
  13. Socket.bind (address);
  14. //Register an event of interest to selector
  15. Server.register (SEL, selectionkey.op_accept);
  16. return sel;
  17. }

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:

[Java]View PlainCopyprint?
  1. /*
  2. * Start monitoring
  3. * */
  4. Public void Listen () {
  5. System.out.println ("Listen on" + port);
  6. try {
  7. While (true) {
  8. //The call will block until at least one event occurs
  9. Selector.select ();
  10. set<selectionkey> keys = Selector.selectedkeys ();
  11. Iterator<selectionkey> iter = Keys.iterator ();
  12. While (Iter.hasnext ()) {
  13. Selectionkey key = (Selectionkey) iter.next ();
  14. Iter.remove ();
  15. Process (key);
  16. }
  17. }
  18. } catch (IOException e) {
  19. E.printstacktrace ();
  20. }
  21. }

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:

[Java]View PlainCopyprint?
  1. /*
  2. * Processing according to different events
  3. * */
  4. protected void process (Selectionkey key) throws ioexception{
  5. //Receive requests
  6. if (key.isacceptable ()) {
  7. Serversocketchannel Server = (Serversocketchannel) key.channel ();
  8. Socketchannel channel = Server.accept ();
  9. Channel.configureblocking (false);
  10. Channel.register (selector, selectionkey.op_read);
  11. }
  12. //Read information
  13. Else if (key.isreadable ()) {
  14. Socketchannel channel = (Socketchannel) key.channel ();
  15. int count = channel.read (buffer);
  16. if (Count > 0) {
  17. Buffer.flip ();
  18. Charbuffer Charbuffer = decoder.decode (buffer);
  19. Name = Charbuffer.tostring ();
  20. Selectionkey SKey = Channel.register (selector, selectionkey.op_write);
  21. Skey.attach (name);
  22. } Else {
  23. Channel.close ();
  24. }
  25. Buffer.clear ();
  26. }
  27. //write event
  28. Else if (key.iswritable ()) {
  29. Socketchannel channel = (Socketchannel) key.channel ();
  30. String name = (string) key.attachment ();
  31. Bytebuffer block = Encoder.encode (Charbuffer.wrap ("Hello" + name);
  32. if (block! = null)
  33. {
  34. Channel.write (block);
  35. }
  36. Else
  37. {
  38. Channel.close ();
  39. }
  40. }
  41. }

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.

Original address: http://blog.csdn.net/wuxianglong/article/details/6612282

Java NIO usage and principle Analysis (d) (EXT)

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.