Principles and usage of Java NiO

Source: Internet
Author: User
Java NiO non-blocking applications are usually used in I/O read/write. We know that the performance bottleneck of system operation is usually in I/O read/write, including port and file operations, in the past, after opening an I/O channel, read () will always wait for reading byte content on the port side. If no content comes in, read () is also silly, this will affect our program to continue to do other things, so the improvement is to open a thread and let the thread wait, but this is also quite resource-consuming.

Java NiO non-blocking technology uses the reactor mode, or the observer mode, to monitor the I/O port for us. If any content comes in, it will automatically notify us, we don't have to enable multiple threads to die. from the outside world, we can achieve smooth I/O reading and writing without blocking.

The emergence of Java NiO is not just an improvement in technical performance. You will find that the network is on the top of it, because it has a milestone. Starting from jdk1.4, Java has started to improve performance-related functions, so that Java can be combined with C, Perl, and other languages in terms of underlying or parallel distributed computing operations.

If you still doubt the performance of Java, it means that your ideas and ideas are completely outdated. Java should be defined in a new term in a year or two. Since jdk1.5, we have to provide support for new performance such as threads and concurrency. Java applications have mature opportunities in Game and other timely fields. After Java has stabilized its middleware position, began to eat away from the traditional C field.

This article briefly introduces the basic principles of NiO. In the next article, we will discuss it in depth in combination with the reactor mode and the famous thread master Doug Lea.

The main principle and application of NiO.

NIO has a main class selector. This is similar to an observer. As long as we tell the selector about the socketchannel to be explored, we will continue to do other things. When an event occurs, it will notify us, return a group of selectionkeys. When we read these keys, we will obtain the socketchannel we just registered. Then, we will read data from this channel, so we can rest assured that the package will be able to read, then we can process the data.

The internal principle of selector is actually to make a round-robin access to the registered channel and continuously round-robin (this algorithm currently). Once a channel is registered, for example, when the data comes, he will stand up and report, hand over a key, and let us read the contents of this channel through this key.

After learning about this basic principle, let's look at it using the code. In terms of usage, there are also two directions. One is thread processing, the other is non-thread processing, and the latter is relatively simple, see 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;

// Use Selector
Selector selector = selector. open ();

// Create a channel and bind it to port 9000
Serversocketchannel SSC = serversocketchannel. open ();
Inetsocketaddress address = new inetsocketaddress (inetaddress. getlocalhost (), 9000 );
SSC. socket (). BIND (Address );

// Enable non-blocking.
SSC. configureblocking (false );

// Register the channel and events we are interested in with Selector
Selectionkey S = SSC. Register (selector, selectionkey. op_accept );
Printkeyinfo (s );

While (true) // continuous polling
{
Debug ("nbtest: Starting select ");

// Selector notifies us of the event we are interested in by using the select method.
Nkeys = selector. Select ();
// If something is registered, its return value will be greater than 0.
If (nkeys> 0)
{
Debug ("nbtest: number of keys after Select Operation:" + nkeys );

// Selector returns a group of selectionkeys
// We obtain 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 ());

// After a key is processed, it is removed from the ready keys list.
I. Remove ();
If (S. isacceptable ())
{
// Obtain the channel we just registered from 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 = new nbtest ();
Try
{
Nbtest. startserver ();
}
Catch (exception E)
{
E. printstacktrace ();
}
}

}

This is an example of Noblock server waiting on port 9000. If we compile a client program, we can perform interactive operations on it, or use Telnet host name 90000 to link it.

By carefully reading this routine, I believe you have a general understanding of NiO principles and usage. In the next article, we will use multiple threads to process the data and create a reactor mode.

From: http://www.jdon.com/concurrent/nio%D4%AD%C0%ED%D3%A6%D3%C3.htm

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.