Java NIO5: Selector 1---theory chapter

Source: Internet
Author: User

Selector Selector

Finally, let's explore the selector. Because the selector content is more, so this article first partial theory to say, after a code, the article does not have any summary, summary, write where to calculate where, only to be able to write the selector to understand, and will be some of the relatively important content bold red.

selectors provide the ability to choose which tasks are already in place, which makes multivariate I/O possible , with ready execution and multivariate selection enabling single threads to efficiently manage multiple I/O channels at the same time.

To some extent, understanding selectors is more difficult and more complicated than understanding buffer and channel classes, because there are three main classes involved, all of which are involved in this whole process, where the execution of the selector is first decomposed into several details:

1. Create one or more selectable channels (Selectablechannel)

2. Register these created channels in the Selector object

3, select the key will remember the developers concerned about the channel, they will also track whether the corresponding channel is ready

4. The developer invokes the Select () method of a Selector object, and when the method returns from the blocking state, the selection key is updated

5. Get the collection of select keys and find the Ready channel, by traversing these keys, the developer can choose what to do with the ready channel.

The operation of the selector is roughly the same number of steps, OK, then go further and look at the three classes associated with the selector.

Selector, selectable channel, and select Key class

Selector (Selector)

The selector class manages the information of a registered channel collection and their readiness state . The channel is registered with the selector, and the selector is used to update the channel's ready state.

Selectable channels (Selectablechannel)

This abstract class provides the public method required to implement the selectivity of the channel, which is the parent class of all channel classes that support readiness checks, FileChannel objects are not selectable because they do not inherit selectablechannel, all socket channels are selectable, Includes the channel obtained from the pipe object. The Selectablechannel can be registered to the Selector object, and it can be set to which of the selectors is interested . A channel can be registered to multiple selectors, but only once for each selector.

Select Key (Selectionkey)

The Select key encapsulates the registration relationship of a particular channel with a specific selector . Calling the Selectablechannel.register () method returns the selection key and provides a token that represents the registration relationship. The selection key contains two bit sets (encoded as integers), indicating the channel operations that the registration relationship is concerned about, and the operations that the channel is already ready for.

Use a UML diagram to describe selectors, selectable channels, and select keys:

Setting up selectors

As mentioned earlier, the function of the selector is to manage the set of registered channels and their readiness state, assuming we have a selector for three socket channels, there may be similar code:

... Selector Selector =




...

This operation is represented by a graph:

The code creates a new selector and then registers the four (already existing) socket channels on the selector, and the operations of interest are different. The Select () method puts the thread to sleep until one of these interesting events occurs, or 10 seconds past, which is called event-driven .

Take a look at the API details of selector:

 public abstract     Class selector{... public static Selector Open () throws IOException; public abstract  Boolean IsOpen (); public abstract void Close () throws IOException; public abstract 

Selector is instantiated by invoking the static factory method open (), as seen in the previous code, where the selector is not a basic I/O object like a channel or a stream----data is never passed through them .

The channel is called register method registered to the selector, from the code can see the register () method to accept a selector object as a parameter, and an integer named Ops parameter, the second parameter represents the channel operation of Concern. In JDK1.4, there are four selectable actions defined: Read, write, connect (connect), and accept.

Note Not all operations are supported on all selectable channels , for example Socketchannel does not support accept.

Using the Select key

Next look at the Select key, the API to select the key is as follows:

PublicAbstractClassselectionkey{PublicStaticFinalIntOp_read;PublicStaticFinalIntOp_write;PublicStaticFinalIntOp_connect;PublicStaticFinalIntop_accept;PublicAbstractSelectablechannel channel ();PublicAbstractSelector Selector ();PublicAbstractvoidCancel ();PublicAbstractBooleanIsValid ();PublicAbstractIntInterestops ();PublicAbstractvoid Iterestops (IntOPS);PublicAbstractIntReadyops ();Publicfinal booleanpublic final boolean< Span style= "color: #000000;" > iswritable (); public final boolean< Span style= "color: #000000;" > isconnectable (); public final boolean< Span style= "color: #000000;" > isacceptable (); public final Object Attach (Object ob); public final Object Attachment ();}                

For these APIs, summarize the points:

1. as mentioned earlier, a key represents a registration relationship between a particular channel object and a particular selector object, and the Channel () method and the selector () method reflect the relationship

2. Developers can use the Cancel () method to end this relationship, you can use the IsValid () method to check whether this valid relationship still exists, you can use the Readyops () method to get the relevant channel is ready to operate

3.2nd refers to the Readyops () method, but we often do not need to use this method, the Selectionkey class defines four easy-to-use Boolean methods to test the state of the channel's readiness for the developer, for example:

If (Key.iswritable ()) {...}

This notation is equivalent to:

if ((Key.readyops () & selectionkeys.opwrite)! = 0) {...}

IsWritable (), isreadable (), isconnectable (), Isacceptable () Four methods can be safely invoked on any of the Selectionkey objects.

4, when the channel is closed, all the relevant keys will be automatically canceled (a channel can be registered to multiple selectors); When the selector is closed, all channels registered to the selector are unregistered and the associated key is immediately canceled.

Three types of keys maintained by selector

A collection of channels registered by the selector maintainer, and any of these registration relationships is encapsulated in the Selectionkey object. Each Selector object maintains a collection of three key types:

PublicAbstractClassselector{...PublicAbstractSet keys ();PublicAbstract Set Selectedkeys (); public abstract int Select () throws IOException; public abstract int Select (long timeout) throws  IOException; public abstract int Selectnow ()  IOException; public abstract void 

By this API look down, these three kinds of keys are:

A collection of registered keys (registered key set)

The collection of registered keys associated with the selector, not all registered keys are valid, returned by the keys () method, and may be empty. The collection of these keys cannot be modified directly, and attempting to do so will cause java.lang.UnsupportedOperationException.

A collection of selected keys (Selected key Set)

A subset of the collection of registered keys, where each member of the collection is a related channel that is judged by the selector to be ready and contained in the interest collection of keys . This collection is returned by the Selectedkeys () method (which may be empty).

The key can be removed directly from this collection, but cannot be added. An attempt to add an element to the collection of selected keys throws Java.lang.UnsupportedOperationException.

A collection of canceled keys (Cancelled key Set)

A subset of the registered Key's collection that contains the keys that the Cancel () method has been called (the key has been invalidated), but they have not been unregistered. This collection is a private member of the Selector object and therefore cannot be accessed directly.

Selection process

Then there is the core selection process of selector. Basically, a selector is a wrapper over a local call to select (), poll (), Epoll (), or similar operating system-specific system calls. But selector does more than simply pass parameters to local code, each operation has a specific process, and the understanding of this process is the basis for managing keys and the state information they represent.

The selection operation is performed by the selector when any of the three forms of select () are invoked. Regardless of which form of invocation, the following steps are executed:

1. The set of canceled keys will be checked. If it is non-empty, the keys in the collection of each canceled key are removed from the other two collections, and the associated channel is unregistered. At the end of this step, the set of canceled keys will be empty.

2. The interest collection of keys in the collection of registered keys is checked, this step ends, and changes to the interest collection do not affect the remaining inspection process. Once the readiness conditions are fixed, the underlying operating system will query to determine the true readiness state of the operations that each channel cares about, depending on the specific select () method call, and if no channel is ready, the thread may block at this point, usually with a timeout value.

3. Step 2 can take a long time, especially if the thread is in a blocked state. The key associated with the selector may be canceled at the same time, and at the end of Step 2, Step 1 will be re-executed to complete the registration of a channel that has been canceled by the key during the selection process.

4.The return value of the select operation is not the total number of channels that have been prepared, but the number of channels that have entered the ready state since the last select () Call . Channels that are ready in the previous call and that are still in place in this call are not counted, and those that are already ready in the previous call but are no longer in the ready state will not be counted into.

Finally, there are two other methods not mentioned in the above selector, which illustrate their meaning:

1, Selectnow ()

Call the Selectnow () method to perform a ready check procedure, but not block , and immediately return 0 if no channel is currently ready.

2, Wakeup ()

Calling the Wakeup () method returns the first selection on the selector that has not yet returned, and if there is currently no selection in progress, the next call to a form of the Select () method will return immediately, and subsequent selection operations will proceed normally.

Java NIO5: Selector 1---theory chapter

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.