Java NiO principle and use

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 the I/O read and write, including port and file operation, in the past, after opening an I/O channel, read () will be waiting on the port side read the byte content, if no content comes in, Read () is also silly and so on, this 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 there is content to come in, will automatically notify us, so that we do not have to open multiple threads death, from the outside, realize the smooth I/O read and write, not blocked.

Java NiO is 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 at the bottom or parallel Distributed computing has been able to keep pace with languages such as C or Perl.

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.

This article is a brief introduction to the fundamentals of NiO, and in the next article, it will be discussed in more detail in conjunction with the reactor model and an article by the famous threading guru Doug Lea.

The main principle and application of NIO.

NIO has a major class selector, which resembles an observer, so long as we tell selector what we need to know, we go on to do something else, and when something happens, he informs us, returns a group of Selectionkey, We read these keys, we get the socketchannel we just registered, and then we read the data from the channel, and we can read the packet, and then we could 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.

Understanding this rationale, 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:


Import java.io.*;
Import java.nio.*;
Import java.nio.channels.*;
Import java.nio.channels.spi.*;
Import java.net.*;
Import java.util.*;

/**
*
* @author Administrator
* @version
*/

public class Nbtest {


/** creates new nbtest */
Public Nbtest ()
{
}

public void StartServer () throws Exception
{
int channels = 0;
int nkeys = 0;
int currentselector = 0;

Using Selector
Selector Selector = Selector.open ();

Establish channel and bind to port 9000
Serversocketchannel SSC = Serversocketchannel.open ();
Inetsocketaddress address = new Inetsocketaddress (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 us
Selectionkey 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 the keys after select operation:" +nkeys);

Selector returns a group of Selectionkeys
We get the channel we just registered from the channel () method in these keys.
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 list
I.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.");
}

}

}


private static void Debug (String s)
{
System.out.println (s);
}


private static void Printkeyinfo (Selectionkey SK)
{
string s = new string ();

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);
}


/**
* @param args the command line arguments
*/
public static void Main (String args[])
{
Nbtest nbtest = new Nbtest ();
Try
{
Nbtest.startserver ();
}
catch (Exception e)
{
E.printstacktrace ();
}
}

}

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.

By reading this routine carefully, I believe you have a rough idea of how NIO works and how to use it, and next, we'll use multithreading to process the data and build a reactor pattern.

Java NiO principle and use

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.