Java NiO Learning-Details (Part Two)

Source: Internet
Author: User

Wu, selector and Selectionkey

Selector is a multiplexer for Selectablechannel objects, why use selector?

The benefit of using only a single thread to handle multiple channels is that fewer threads are needed to process the channel. In fact, you can process all the channels with just one thread. For the operating system, context switching between threads is expensive, and each thread consumes some of the system's resources, such as memory. Therefore, the less threads you use, the better.

However, it is necessary to keep in mind that modern operating systems and CPUs are performing more and more well in multitasking, so the overhead of multithreading is getting smaller over time. In fact, if a CPU has multiple cores, not using multitasking may be a waste of CPU power. Anyway, the discussion about that design should be in another different article. Here, it is sufficient to know that using selector can handle multiple channels.

Specific implementation steps:

1, create Selector:selector Selector = Selector.open ();

2. Register the channel with an event of interest to the channel in selector:

Using the Selectablechannel.register () method to implement

Channel.configureblocking (false= channel.register (selector,    selectionkey.op_read);

When used with selector, the channel must be in non-blocking mode. This means that FileChannel cannot be used with selector because FileChannel cannot switch to nonblocking mode. Socket channels are available.

The second parameter of the register () method is a "interest collection", meaning what events are of interest when listening to the channel through selector. You can listen to four different types of events: Connect,accept,read,write.

The channel triggers an event that means that the event is ready. Therefore, a channel successfully connected to another server is called "Ready to connect." A server socket channel is ready to receive new incoming connections called "Receive ready." A data-readable channel can be said to be "read-ready". The channel waiting to write the data can be said to be "write ready".

These four events are represented by the four constants of Selectionkey: Selectionkey.op_connect, Selectionkey.op_accept, Selectionkey.op_read, SelectionKey.OP _write

If you are interested in more than one event, you can use the bitwise OR operator to concatenate the constants as follows: intinterestSet = SelectionKey.OP_READ | SelectionKey.OP_WRITE;

3. Save Selectionkey Object

When the channel is registered with selector, the Register () method returns a Selectionkey object. This object contains some of the attributes you are interested in: Interest collection, ready collection, Channel, Selector, additional objects (optional)

(1), interest collection is the collection of events of interest that you choose. You can read and write interest collections through Selectionkey, like this:

int interestset = selectionkey.interestops (); Boolean isinterestedinaccept  = (Interestset & selectionkey.op_accept) = = Selectionkey.op_accept ;boolean isinterestedinconnect = interestset & selectionkey.op_connect; Boolean isinterestedinread    = interestset & selectionkey.op_read; Boolean isinterestedinwrite   = interestset & selectionkey.op_write;

With the bitwise AND action interest collection and the given Selectionkey constant, you can determine whether a certain event is in the interest collection.

(2), the Ready collection is a collection of operations that the channel is already prepared for. After a selection (Selection), you will first access this ready set.

int readyset = Selectionkey.readyops ();

You can use methods like the interest collection to detect what events or operations in the channel are ready. However, you can also use the following four methods, all of which return a Boolean type:

Selectionkey.isacceptable (); selectionkey.isconnectable (); selectionkey.isreadable (); selectionkey.iswritable ();

(3), Channel + Selector

is the channel and selector reference at the time of registration

(4), additional objects

You can attach an object or more information to the Selectionkey, which makes it easy to identify a given channel. For example, you can attach a buffer that is used with a channel, or an object that contains aggregated data. Here's how to use it:

= Selectionkey.attachment ();

You can also attach objects when registering a channel with the selector using the register () method. such as: Selectionkey key = Channel.register (selector, selectionkey.op_read, theobject);

4. Select channel through selector in single thread

Once you have registered one or more channels with selector, you can invoke several overloaded select () methods. These methods return those channels that you are interested in (such as connecting, accepting, reading, or writing) that are already ready. In other words, if you are interested in a "read-ready" channel, the Select () method returns those channels where the read event is already ready.

the int select () blocks to at least one channel ready for the event you are registering.
The int select (Long timeout) and select (), in addition to the longest block timeout milliseconds (parameters).
int Selectnow () does not block, no matter what channel is ready to return immediately ( Translator Note: This method performs a non-blocking selection operation.) If no channel becomes selectable since the previous selection operation, this method returns 0 directly .

The int value returned by the Select () method indicates how many channels are ready. That is, how many channels become ready since the last time the Select () method was called. If the Select () method is called, because a channel becomes ready and returns 1, if the Select () method is called again, it returns 1 again if the other channel is ready. If no action is made on the first ready channel, there are now two ready channels, but only one channel is ready between each select () method call.

5. Get all previous selected Selectionkey through Selectedkeys (), get to channel through Selectionkey

Once the Select () method is called and the return value indicates that one or more channels are ready, you can then access the Ready channel in the selected keyset (selected key set) by calling selector's Selectedkeys () method. As shown below:

set<selectionkey> Selectedkeys = Selector.selectedkeys ();

When the Channel is registered with selector, the Channel.register () method returns a Selectionkey object. This object represents the channel registered to the selector. These objects can be accessed through the selector Selectedkeys () method.

You can traverse this selected set of keys to access the Ready channel. As follows:

Set Selectedkeys =Selector.selectedkeys (); Iterator Keyiterator=selectedkeys.iterator (); while(Keyiterator.hasnext ()) {Selectionkey key=Keyiterator.next (); if(Key.isacceptable ()) {//a connection is accepted by a serversocketchannel.}Else if(Key.isconnectable ()) {//A connection is established with a remote server.}Else if(Key.isreadable ()) {//A channel is ready for reading}Else if(Key.iswritable ()) {//A channel is ready for writing} keyiterator.remove ();}

This loop iterates through each key in the selected key set and detects the ready event for the channel corresponding to each key.

Note the Keyiterator.remove () call at the end of each iteration. Selector does not remove the Selectionkey instance from the selected key set itself. You must remove yourself when you are finished processing the channel. The next time the channel becomes ready, selector will put it in the selected key set again.

The channel returned by the Selectionkey.channel () method needs to be transformed into the type you want to handle, such as Serversocketchannel or Socketchannel.

6. Other related operations

WakeUp ()

A thread is blocked after invoking the Select () method, and there is a way to return it from the Select () method, even if no channel is ready. Just let the other thread call the Selector.wakeup () method on the object on which the first thread invokes the Select () method. Blocking the line routines on the Select () method immediately returns.

If there are other threads calling the wakeup () method, but no thread is currently blocking on the Select () method, the next thread that calls the Select () method "wakes up" immediately (wake up).

Close ()

Calling its close () method after the selector is exhausted closes the selector and invalidates all Selectionkey instances registered on the selector. The channel itself is not closed.

Full Use example

Selector Selector =Selector.open (); Channel.configureblocking (false); Selectionkey Key=Channel.register (selector, selectionkey.op_read); while(true) {  intReadychannels =Selector.select (); if(Readychannels = = 0)Continue; Set Selectedkeys=Selector.selectedkeys (); Iterator Keyiterator=Selectedkeys.iterator ();  while(Keyiterator.hasnext ()) {Selectionkey key=Keyiterator.next (); if(Key.isacceptable ()) {//a connection is accepted by a serversocketchannel.}Else if(Key.isconnectable ()) {//A connection is established with a remote server.}Else if(Key.isreadable ()) {//A channel is ready for reading}Else if(Key.iswritable ()) {//A channel is ready for writing} keyiterator.remove (); }}

Java NiO Learning-Details (Part Two)

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.