NIO Beginner Notes

Source: Internet
Author: User

    • About NIO

Java NIO, Java non-blocking io (Java nonblocking I/O), is a set of operational I/O toolkits added after Jdk1.4 and is called Java New io.

    • NiO is going to solve the problem

NiO to solve the problem online explanation a lot, such as bank number, restaurant ordering and so on. These columns are no longer specifically duplicated, in effect providing higher productivity using existing resources.

It reminds me of the story in the textbook when I was studying politics, and capitalists often try to improve their productivity in order to earn more surplus value. How to improve it? For example, a car manufacturer has several production lines (one production line for all parts of the car), each with the same number of workers, and each worker is responsible for a production process, which means that the number of workers who produce the engine and the tires is the same, But it is clear that the production of the engine takes much longer than the tires, so the worker who produces the engine on each production line is often working at full capacity, and the workers who produce the tires are idle, so the productivity is low. Therefore, the manufacturers broke the production line of this kind of car all aspects of the model, instead of a car parts a production line, then the number of workers employed in the engine line must be more than the tire production line, so that each production line of workers will not idle, through the rational allocation of resources to maximize the use of workers value, Increase production efficiency and earn surplus value.

And how to improve production efficiency through rational allocation of resources is the problem that NIO should solve in the field of computer IO.

    • Synchronous/asynchronous, blocking/non-blocking

Synchronization and Asynchrony are for the interaction of the application and the kernel:

Synchronization refers to the user process triggering IO operation and waiting or polling to see if the IO operation is ready, asynchronous refers to the user process triggered IO operations to start doing their own things, and when the IO operation has been completed will be the completion of the IO notification.

Blocking and non-blocking are the different ways in which a process can access data, depending on the readiness state of an IO operation, which is a way of reading or writing an operation function:

The read or write function will wait for blocking mode, and the read or write function will return a status value immediately if it is not blocked.

    • Reactor (reactor) mode:

  

The reactor mode is applied to the synchronous IO scenario, the event splitter waits for an event to occur or the operational state changes (such as the file descriptor can read or write, or the socket can read and write), the event splitter will pass this event to the pre-registered event handler function or callback function, The latter to do the actual read and write operations.

There are several roles in the reactor mode:

1. Reactor

The event splitter, whose core is selector, is responsible for responding to the IO event, and once it happens, the broadcast is sent to the appropriate handler for processing. Specifically for a selector and a serversocketchannel. Serversocketchannel is registered to selector, gets the Selectionkey binding a acceptor (which can also be understood as a handler).

The reference code is as follows:

1 Importjava.io.IOException;2 Importjava.net.InetAddress;3 Importjava.net.InetSocketAddress;4 ImportJava.nio.channels.SelectionKey;5 ImportJava.nio.channels.Selector;6 ImportJava.nio.channels.ServerSocketChannel;7 ImportJava.util.Iterator;8 ImportJava.util.Set;9 Ten /** One * Reactor mode is used to solve multiple user access concurrency problems A  */ -  Public classReactorImplementsRunnable { -      Public FinalSelector Selector; the      Public FinalServersocketchannel Serversocketchannel; -  -      PublicReactor (intPortthrowsIOException { -selector =Selector.open (); +Serversocketchannel =Serversocketchannel.open (); -Inetsocketaddress inetsocketaddress =Newinetsocketaddress (Inetaddress.getlocalhost (), port); + serversocketchannel.socket (). bind (inetsocketaddress); AServersocketchannel.configureblocking (false); at  -         //register the channel with selector -Selectionkey Selectionkey =Serversocketchannel.register (selector, selectionkey.op_accept); -  -         //use Selectionkey's attache function to bind acceptor if there's something that triggers acceptor -Selectionkey.attach (NewAcceptor ( This)); in     } -  to @Override +      Public voidrun () { -         Try { the              while(!thread.interrupted ()) { * Selector.select (); $Set<selectionkey> Selectionkeys =Selector.selectedkeys ();Panax NotoginsengIterator<selectionkey> it =selectionkeys.iterator (); -                 //Selector The following traversal occurs if a channel is found to have a op_accept or read event.  the                  while(It.hasnext ()) { +                     //An event is triggered for the first time by a accepter thread, Socketreadhandler ASelectionkey Selectionkey =It.next (); the Dispatch (Selectionkey); + selectionkeys.clear (); -                 } $             } $}Catch(IOException e) { - e.printstacktrace (); -         } the     } - Wuyi     /** the * Run acceptor or Socketreadhandler -      *  Wu      * @paramKey -      */ About     voidDispatch (Selectionkey key) { $Runnable r =( Runnable) (Key.attachment ()); -         if(r! =NULL) { - R.run (); -         } A     } +  the}
View Code

2. Acceptor

Can also be understood as a handler, this handler is only responsible for creating a specific processing IO request Handler, If reactor broadcasts Selectionkey creates a handler responsible for binding the corresponding Socketchannel to selector. The next time I have an IO event, I call the handler to handle it.

The reference code is as follows:

1 Importjava.io.IOException;2 ImportJava.nio.channels.SocketChannel;3 4  Public classAcceptorImplementsRunnable {5     PrivateReactor Reactor;6 7      Publicacceptor (Reactor Reactor) {8          This. Reactor =reactor;9     }Ten  One @Override A      Public voidrun () { -         Try { -Socketchannel Socketchannel =reactor.serverSocketChannel.accept (); the             if(Socketchannel! =NULL){ -                 //call handler to process channel -                 NewSocketreadhandler (Reactor.selector, socketchannel); -             }                 +}Catch(IOException e) { - e.printstacktrace (); +         } A     } at}
View Code

3. Handler

Specific event handlers, such as Readhandler, Sendhandler,readhandler, are responsible for reading the data in the cache, and then invoking a work processing thread to process the read data. When the handler is initialized for a socketchannel,acceptor, the Socketchannel is registered to the selector of reactor, and the Selectionkey is bound to handler, This will call the handler next time.

The reference code is as follows:

1 Importjava.io.IOException; 2 ImportJava.nio.ByteBuffer; 3 ImportJava.nio.channels.SelectionKey; 4 ImportJava.nio.channels.Selector; 5 ImportJava.nio.channels.SocketChannel;6 7  Public classSocketreadhandlerImplementsRunnable {8     PrivateSocketchannel Socketchannel;9 Ten      PublicSocketreadhandler (Selector Selector, Socketchannel Socketchannel)throwsIOException { One          This. Socketchannel =Socketchannel; ASocketchannel.configureblocking (false); -  -Selectionkey Selectionkey = socketchannel.register (Selector, 0); the  -         //The run method of this class is called when the Selectionkey is bound to this handler and the next event is triggered.  -         //See Dispatch (Selectionkey key) -Selectionkey.attach ( This); +  -         //The Selectionkey is also marked as readable for reading.  + Selectionkey.interestops (selectionkey.op_read); A selector.wakeup (); at     } -  -     /** - * Processing Read Data -      */ - @Override in      Public voidrun () { -Bytebuffer InputBuffer = bytebuffer.allocate (1024); to inputbuffer.clear (); +         Try { - Socketchannel.read (inputbuffer); the             //Activate the thread pool to process these request *             //RequestHandle (New Request (SOCKET,BTT)); $}Catch(IOException e) {Panax Notoginseng e.printstacktrace (); -         } the     } +}
View Code

To sum up, we can understand the above-mentioned role of the refinement of the workload of a job refinement, or re-assigned, the person to do the special, so that the maximum use of the value of each role, improve efficiency.

NIO Beginner Notes

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.