Java NIO Selector

Source: Internet
Author: User

Recently learn <java nio> in the selector, so combined with selector source code, write a little notes.

I. What is selector?

When it comes to selector, I cannot but mention Selectablechannel,selectionkey. Their relationship is:

1. Selector (Selector)

The Selector class manages the information of a registered channel collection and their readiness state.

2. Selectable channels (Selectablechannel)

this abstract class provides the public method required to implement the optional channel. It is all supported ready to check

Channel the parent class of the class.

Selectablechannel can be registered to the Selector object and can be specified for that selector,

that The operation is of interest

Note: FileChannel objects are not selectable because they do not inherit Selectablechannel

3. Select Key (Selectionkey)

The Select key encapsulates the registration relationship of a particular channel with a specific selector.

Two. Collection of selector

Each Selector object maintains 3 sets (set), and the elements of each collection are select keys (selectionkey).

   1. ♦ registered key ♦
The collection of registered keys associated with the selector. Not all registered keys are still valid!
A. To get this collection, you can call the following method:
 Public Abstract set<selectionkey> keys ();
B. Want to add a key directly to this collection (a selector keyset),not supported!C. To delete a key directly from this collection,not supported ! 2.♦ the selected key ♦Each member of this collection is a related channel that is determined by the selector (in the previous selection operation) to be ready and contained in the interest collection of the key.      is a subset of the collection of registered keys. A. To get this collection, you can call the following method:
 Public Abstract Set<selectionkey> Selectedkeys ();

B. Want to add a key directly to this collection, not supported!

C. To remove a key from this collection directly, you can call the following method:

Java.util.Set.remove (Object o);
Or
Java.util.Iterator.remove ();

3.♦ canceled key ♦

A subset of the registered Key's collection that contains the key that the Cancel () method has been called (the key has been invalidated).

But they haven't been written off yet.

When a key is canceled, it is added to this collection. Cancellations can be done by:

→ Close the channel associated with the key

→ Call the key's Cancel () method.

In a newly initialized Selector object, these three collections are empty.

As you can see from the summary above, it may be confusing for some collections to operate as "unsupported" cases.

!! PLEASE note!!

"Not supported" refers to the " direct " operation. If we cannot do this:

Error code!!
Set<selectionkey> keyset = Selector.keys (); Keyset.clear ();

How can it be operated "indirectly"? You need to understand selector's workflow first.

Three. Selector's Work Flow

1. Open a Selector

Selector Selector = Selector.open ();
At this point the selector is new (just initialized), and the three collections are empty.

2. Register the channel with the selector


Channel2.register (selector, selectionkey.op_write);
Channel3.register (Selector, Selectionkey.op_read | Selectionkey.op_write);
This assumes that 3 channel is already present.
At this point, the registered collection consists of 3 keys.
Selected collection and canceled collection are empty

3. Call Selector.select ()

Selector.select ();

The following checks are performed:

A. Check the collection of canceled keys. If not NULL, the keys in this collection are removed from the other 2 collections .

of Course the relevant The channel is logged off. And this collection is emptied.

B. Check the interest collection of keys for the collection of registered keys.

The above steps are called "Ready conditions", then the underlying operating system will be queried according to the conditions just now.

To determine the true readiness state of the operations that each channel cares about .

When determining the channel readiness State:

A. For a channel that is not yet ready, no action will be taken.

B. For those channels that are at least ready for an operation in the interest collection, one of the following 2 operations will be performed:

B1. If the key of the channel is not already in the collection of the selected key, the Ready collection of the key is emptied and then represents

The operating system discovers that the current channel is ready for the operation of the bit mask will be set.

B2. If the key is in the selected Key's collection, the Ready collection of keys is represented by the operating system discovery that is currently prepared

Good operation bit mask update

Here's what I drew:

The diagram on the left is Selector.select () before execution:

A. The channel is registered to selector, so the selector keys collection contains Selection Key (recorded as K). and K is clear.

The channel is a registered relationship between C and selector for S.

B. The interest OPS value for K is read, which indicates that the channel is interested in read operations. Note: At this point, the selected keys collection in S is empty.

On the right, after Selector.select () is executed:

The read OPS value for K reads, which indicates that the channel reading is ready.

K is added to the selected keys collection in S.

Here I add 2 points:

* Selector.select () is a system call.

* After a SELECT () call, the change to "ready condition" is not affected by the result of this select ().

Select () blocks the calling thread and returns when the following conditions are true:

* One or more channels are ready

* This select.wakeup () method is called

* The calling thread is interrupted (interrupted)

  

Select () is a return value, but only returns the number of keys in the collection that are not the selected key .

  Instead, the number of keys that the Ready collection was changed at the time of this call to select ().

4. Get selector selected keys

After the 3rd step of the Select () method is executed, the selector selected keys is updated. Then we go through the collection.

As I said earlier, getting this collection can be used with the Selectkeys () method.

When you traverse this collection, each key is processed, and the key is removed from the collection .

Removing this step is important:

Because selector adds selection key to the selected keys collection, it does not delete the key.

We need to remove it manually, which is equivalent to telling selector, "We've seen and processed this key during traversal."

Indicated Readyops ", so selector knew that the key associated with the channel, the relevant readiness conditions have been

It doesn't work (because we're done), it's the next select () operation and the channel associated with this key has a new

Ready condition, the key's readyops is emptied and reset to reflect the new state's value.

    

Java NIO Selector

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.