Principles and Applications of Java NIO

Source: Internet
Author: User

A previous project started with bio, or block Io, and then replaced bio with NIO, or non-blocking IO, because of some performance issues.

Let's talk about what's the downside of bio. Why use NiO:

Use TCP in Java as an example to explain:

We know that in the client Java call to the Connect method will block, the call to read will also block the time it is not read to be blocked there, and the server side, call the Accept () method will block, call the Read method will also block this will have a significant performance impact.


Next we explain the principle of nio, or TCP, for example, now many frameworks are using NIO like the Mina framework, as well as Java in the RMI call, etc. will be used in NiO, if the heap NiO principle is not clear, it is easy to create performance, the problem:

The main concepts in 1.NIO:

The first concept is the channel, that is, channels, in the bio is through the input and output stream to interact, but these flows are unidirectional, not bidirectional flow, then in NIO with channel instead of the flow, as a communication, then the channel is bidirectional, that is, the way data flow is bidirectional, Also on the server or the client, who wants to read the data, read from the channel, who wants to write data to the channel to write data. Now it's possible to replace the stream with a pipe, and it's not, of course, so design to the second concept.

        The second main concept is that Selector,nio is the concept to solve the problem of blocking, in this concept we have to know the way nio work, NIO is non-blocking because, NiO is event-driven, not bio, through blocking implementation, so a little unclear, then we illustrate, first of all, say what is event-driven, such as you do not charge, and the phone is not able to receive text messages, and you can not access the Internet, then you have to run to the business hall to view, is not owed fees, And if the business hall doesn't open, you go home and do other things. And blocking is what, that is, if the business hall does not open the door, you have been waiting at the door of the business Hall, know that the door to check you only go home, of course, you can not do anything in the business hall. Then my nio is need you constantly to see whether the opening of the business Hall, is to run a few more trips. Then the problem arises, if you go home, this time the business Hall door opened, but you did not go, it would not be missed. and NiO's solution to this problem is this, if you are familiar with the people in the business hall, then maybe someone will put in a container to say, if you want to check the charges and go to the container to take the key, if the container is a box, then if you miss, you can go to the box and open the door to check the key. Then selector is actually equivalent to this container, and the event is equivalent to the key, each time if you want to see no data need to read, then walk through the box, if there is a key to read the event in the box, then go to the pipeline to read, because there are many events in the communication process, such as reading (read), Write (write), connect (connect), receive connection (accept), then it is equivalent to have four kinds of keys, see different time to perform, different operation. So this time the new problem comes again, if your mobile phone is mobile, and put the key box in a public place, that is, the mobile people can put the key in this box, Unicom people can also put the key in this box, then if you take the key, you take the key, and then you open the door of the Unicom, At this time you are not in the wrong room, the room is the equivalent of channel,selector is public, you get the other connection time, then you are not in the wrong channel, the other situation is you do not know, take it, to which channel to write data or read data, This is the third important concept that emerges.

The third main concept is register registration, is to register selector to the channel, that is, each channel a selector, of course, some time selector can be the channel common, but recommend a channel register a selector , so that when using your channel, you can not get other channel events, that is, mobile and unicom each has a box, you go to different places to take the keys, you will go to different rooms. But there will be problems, if you just want to check the mobile phone bill, but the mobile box is placed in two, the key is a mobile business Hall key, one is the door key of the mobile business Hall, but you point from the front door into, do not want to enter from the back door, that is, you are not interested in the back door that key, We certainly do not go to get him, but in the program is not so smart, that is, in the program, it must be seen that the key is not the front door, but it is to see this action in the program is also time-consuming, in order to solve this problem, there is a fourth concept.


The fourth main concept, also can be said to be a specification, is not mandatory, is to set the selector in the time type, if said selector only interested in reading, then other types of time once arrived, will be selector ignored that is not, put time into selector, You tell the people in the business hall not to put the back door key in the box.


2. Working principle:

After the above four concepts elaborated, our team work principle already very clear, is a communication node, first establishes a storage event selector, then you also must register the interest time, otherwise any event will not be put into, selector, then is obtains the pipeline, Because the pipeline always needs to have one side of the communication to establish, after establishing the channel, then give the IP and port you want to connect, then bind the IP and port on the pipeline, then this pipeline will be based on IP and port to find the target machine you want to communicate, then the other side will certainly be on an existing pipeline, listen to this request, If listening to, then the equivalent of the pipeline, on the docking, and then to the pipeline to register selector, the pipeline both sides of the node, all need to register their own selector, so you can communicate. A node, to query the selector, query to the event, then response time, or write data to the channel, or read the data from the channel, so that you can communicate. The basic principle is this, but in the specific implementation of the time there are some details need to understand, there is a TCP connection, in the client and server side is a little different, because the pipeline is divided into ordinary pipeline and server pipeline, but there is no big difference, is the server pipeline is mainly used to monitor the connection, Mainly interested in the accept event, while the common pipeline is mainly interested in reading and writing events. To help everyone better understand, here is I write a server code and client code, you can refer to, basically is a client connection, then on the server side to establish a thread for processing.


Server code:


Package Com.test;import Java.io.ioexception;import Java.net.inetsocketaddress;import java.nio.bytebuffer;import Java.nio.channels.channel;import Java.nio.channels.closedchannelexception;import Java.nio.channels.SelectionKey; Import Java.nio.channels.selector;import Java.nio.channels.serversocketchannel;import Java.nio.channels.socketchannel;import Java.util.iterator;public class Nioserver {//server for listening selector private selecto          R selector; public void Initserver (int port) throws ioexception{//Get a serversocket channel Serversocketchannel serversocketchannel=         Serversocketchannel.open ();     Set to non-blocking serversocketchannel.configureblocking (false);     Bind Port Serversocketchannel.socket (). bind (New Inetsocketaddress (port));     Get a listener this.selector=selector.open ();     Bind the Channal to selector serversocketchannel.register (selector, selectionkey.op_accept);        } Static class Tcpservice implements runnable{private Selector serviceselector; PRivate Socketchannel Servicechannel;    Public Tcpservice (Socketchannel servicechannel) {this.servicechannel=servicechannel;    } private void Init () throws ioexception{Serviceselector=selector.open ();    Register read event, bind Servicechannel.register (Serviceselector, Selectionkey.op_read); } @Overridepublic void Run () {try {init ();//Polling Read event int count=10;while (count>0) {count--;//First write a piece of data servicechannel.write    (Bytebuffer.wrap (New String ("Hello client"). GetBytes ());    Serviceselector.select ();    Iterator<selectionkey> It=serviceselector.selectedkeys (). Iterator ();    while (It.hasnext ()) {Selectionkey key=it.next ();    It.remove ();     if (key.isreadable ()) {Bytebuffer buffer = bytebuffer.allocate (10);     Servicechannel.read (buffer);     String Msg=new string (Buffer.array ());     SYSTEM.OUT.PRINTLN ("Server received message:" +msg);    Servicechannel.write (Bytebuffer.wrap ("Serverack". GetBytes ())); }}}} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktracE ();}} }//Listening connection public void listen () throws ioexception{System.out.println ("The server started successfully!     ");     while (true) {//Poll connection Event Selector.select ();        Traverse Connection Event iterator<selectionkey> It=selector.selectedkeys (). Iterator ();        while (It.hasnext ()) {Selectionkey key=it.next ();        In case of repeated processing it.remove (); if (key.isacceptable ()) {//Get server channel Serversocketchannel serversocketchannel= (Serversocketchannel) Key.channel ()        ;        Gets and the client connection Channel Socketchannel channel=serversocketchannel.accept ();        Set to non-blocking channel.configureblocking (false);        Start a service thread System.out.println ("Turn on a service thread");            Runnable service=new Tcpservice (channel);        New Thread (Service). Start (); }}}} public static void Main (string[] args) throws IOException {Nioserver nioserver=new nioserv ER (); nioserver.initserver (9768); Nioserver.listen ();}}


Client code:


Package Com.test;import Java.io.ioexception;import Java.net.inetsocketaddress;import java.nio.bytebuffer;import Java.nio.channels.selectionkey;import Java.nio.channels.selector;import Java.nio.channels.socketchannel;import Java.util.iterator;public class Nioclient {private Selector connectselector;public void init (String ip,int port) throws I oexception{//get Socketchannelsocketchannel Socketchannel=socketchannel.open ();// Set to non-blocking socketchannel.configureblocking (false);//Get Connection selector connectselector=selector.open ();// Connect Socketchannel.connect (new inetsocketaddress (IP, port));//Register Connection Event Socketchannel.register (Connectselector, Selectionkey.op_connect);} public void Listen () throws Ioexception{while (True) {Connectselector.select ();iterator<selectionkey> it= Connectselector.selectedkeys (). iterator (); while (It.hasnext ()) {Selectionkey key=it.next (); It.remove (); if ( Key.isconnectable ()) {Socketchannel channal= (Socketchannel) Key.channel (); if (channal.isconnectionpending ()) { Channal.finishconnect ();} Channal.configUreblocking (false); Channal.write (Bytebuffer.wrap ("Hello Server". GetBytes ())); Channal.register (Connectselector, Selectionkey.op_read);}          else if (key.isreadable ()) {//server can read message: Gets the event that occurs when the socket channel Socketchannel channel = (Socketchannel) key.channel ();          Creates a read buffer Bytebuffer = bytebuffer.allocate (10);          Channel.read (buffer);          byte[] data = Buffer.array ();          String msg = new string (data). Trim ();          SYSTEM.OUT.PRINTLN ("Client received message:" +msg);          Bytebuffer Outbuffer = bytebuffer.wrap ("Client yes". GetBytes ()); Channel.write (Outbuffer);//Send message back to client}}}}public static void main (string[] args) throws IOException {nioclient n    Ioclient=new nioclient ();    Nioclient.init ("127.0.0.1", 9768); Nioclient.listen ();}}



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Principles and Applications of Java NIO

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.