Java NiO usage and Principle Analysis (4)

Source: Internet
Author: User

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?
  1. /*
  2. * Register an event
  3. **/
  4. Protected selector getselector () throws ioexception {
  5. // Create a selector object
  6. Selector sel = selector. open ();
  7. // Create a selectable channel and configure the non-blocking mode
  8. Serversocketchannel Server = serversocketchannel. open ();
  9. Server. configureblocking (false );
  10. // Bind the channel to the specified port
  11. Serversocket socket = server. socket ();
  12. Inetsocketaddress address = new inetsocketaddress (port );
  13. Socket. BIND (Address );
  14. // Register an event of interest with Selector
  15. Server. Register (SEL, selectionkey. op_accept );
  16. Return sel;
  17. }

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?
  1. /*
  2. * Start listening
  3. **/
  4. Public void listen (){
  5. System. Out. println ("listen on" + port );
  6. Try {
  7. While (true ){
  8. // The call will be blocked 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 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?
  1. /*
  2. * Handle different events
  3. **/
  4. Protected void process (selectionkey key) throws ioexception {
  5. // Receives the request
  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 = 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 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)

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.