"Java" "NiO" 7, Java NiO Selector

Source: Internet
Author: User

Selector is a component of Java NIO that can examine the channel of one or more nio, and decide which channel is ready for read and write. In this way, a single thread can manage multiple channel, that is, multiple network connections.

Why use Selectors

The advantage is that fewer threads handle multiple channels. In fact, you can use a thread to handle all the channels. The switching of threads in the operating system is very resource-intensive, and each thread itself consumes some resources (memory). So the fewer threads you use, the better!

Now that the operating system and CPU are becoming more and more good on multitasking, the overhead of multithreading becomes even smaller. In fact, if a CPU has multiple cores, it may be wasteful to use multiple threads. Anyway, the design discussion should be in another article that says. Here, it is enough to know that using selector, single-threaded to handle multi-channel.

Creating selectors

Created by calling the Selector.open () method.

Register Channel

Channel.configureblocking (false); Configure channel to non-blocking mode
Channel.register (selector,selectionkey.op_accept); Register by this method

Using Selector,channel must be non-blocking mode. means that the FileChannel does not use selector because FileChannel cannot be switched to nonblocking mode. Socketchannel can be used normally.

Note the second parameter of the Register method. This is a collection of interests, meaning what kind of event is interesting when listening to the channel through selector. There are several:
1. Connect
2. Accept
3. Read
4. Write

A channel that triggers an event means that the event is ready. Therefore, a channel and server connection is successful is the connection is ready. Serversocketchannel Accept the connection is ready to accept. A channel with data ready to be read is ready to read. A channel ready to write data is ready to write.
These four events are defined by the four constants of Selectionkey:
1, Selectionkey.op_connect
2, Selectionkey.op_accept
3, Selectionkey.op_read
4, Selectionkey.op_write
If you are interested in multiple events, you can write them as follows:

int interestset = Selectionkey.op_read | Selectionkey.op_write;

After the article will be back to the interest set to explain.

Selectionkey ' s

As mentioned earlier, when you register a channel via selector, the Register method returns a Selectionkey object that contains some of the attributes you are interested in:
· The interest set
· The Ready Set
· The Channel
· The Selector
· An attached object (optional)

Interest Set

The interest collection is a collection of events that you are interested in. You can read and write interest collections through Selectionkey, as follows:

int interestset = Selectionkey.interestops ();

Boolean isinterestedinaccept = Interestset & selectionkey.op_accept;
Boolean isinterestedinconnect = Interestset & selectionkey.op_connect;
Boolean isinterestedinread = Interestset & selectionkey.op_read;
Boolean isinterestedinwrite = Interestset & selectionkey.op_write;

You can use & to find out if an event is a collection of interests.

Ready Set

The Ready collection is the channel for which operations are already in place. After a single selection, you will first access the Ready collection, as follows:

int readyset = Selectionkey.readyops ();

You can also test which operations are ready by &, as mentioned above. However, you can also get the following methods:

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

Channel + Selector

Accessing the Channel+selector via Selectionkey is simple, as follows:

Channel channel = Selectionkey.channel ();

Selector Selector = Selectionkey.selector ();

Attaching Objects

You can attach an object or more information to a selectionkey to identify a specific channel. For example, you can attach a buffer that is used with a channel or an object that contains a lot of aggregated data, as follows:

Selectionkey.attach (theobject);

Object attachedobj = Selectionkey.attachment ();

You can also attach objects when you register.

Selectionkey key = Channel.register (selector, selectionkey.op_read, theobject);

Selecting Channels via a Selector

Once you have registered multiple channels through selector, you can call the Selecto method. These methods return an event-ready channel for the interest collection (connect, receive, read, write). In other words, if you are interested in a read-ready channel, you will return to the read-ready channel through the Select method.
The following is the Select method:
int Select ()
int Select (Long timeout)
int Selectnow ()
The Select () method blocks until at least one channel is ready for the event that you register.
Select (Long timeout), like select (), has a time-out in addition to blocking.
Selectnow () does not block, no matter what channel, ready to return immediately.
The int returned by the Select () method indicates how many channels are ready, that is, how many channels are ready since the last time the Select () method was called. If you call the Select method to return 1, indicating that there is a channel ready, you call back 1 again, indicating that the other channel is ready. If you do nothing with the first ready channel, you now have two ready channels, but only one channel is ready for each Select method call.

Selectedkeys ()

Once you invoke a select () method and return a value indicating that one or more channels are ready, you can access the Ready channel via the selected key collection, by invoking the Selectedkeys method, as follows:

Set Selectedkeys = Selector.selectedkeys ();

When you register a channel event, a Selectionkey object is returned. This object represents the channel registered on the selector. You can access these keys through Selectedkeyset. As follows:

Set<Selectionkey> Selectedkeys = Selector.selectedkeys ();Iterator<Selectionkey> keyiterator = Selectedkeys.iterator (); while(Keyiterator.hasnext ()) {SelectionkeyKey = Keyiterator.Next();if(Key.isacceptable ()) {//A connection is accepted by aServersocketchannel. }Else if(Key.isconnectable ()) {//A connection is established with a remote server. }Else if(Key.isreadable ()) {//A channel is ready forReading}Else if(Key.iswritable ()) {//A channel is ready forWriting} keyiterator.remove ();}

This loop iterates through the selected key collection. and detect channel readiness events for 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 what you need, such as Serversocketchannel,socketchannel.

WakeUp ()

A thread calls the Select method to block, and even if there is no ready channel, the Select method can be returned. Let other threads call the wakeup method through the selector object that just called the Select method. A thread that blocks on the Select method returns immediately.
If another thread calls wakeup, but no thread is currently blocking the Select, the next thread that invokes the Select method wakes up immediately.

Close ()

Run out of selector to call the Close method. Turns off selector and invalidates all keyset registrations on the selector. The channel itself does not shut down.

Full instance
Package NiO;Import Java. IO. IOException;Import Java. NET. Inetsocketaddress;Import Java. NET. ServerSocket;Import Java. NiO. Channels. Selectionkey;Import Java. NiO. Channels. Selector;Import Java. NiO. Channels. Serversocketchannel;Import Java. Util. Iterator;Import Java. Util. Set;public class Selectordemo {public static void main (string[] args) throws IOException {//Open server Socket channel Serv Ersocketchannel SSC = Serversocketchannel. Open();Non-blocking mode SSC. configureblocking(false);Gets the server socket associated with this channel ServerSocket SS = SSC. Socket();Service binding SS. Bind(New Inetsocketaddress (8990));Open a selector Selector Selector = Selector. Open();Register Channel event Selectionkey Registerkey = SSC on this selector. Register(Selector, Selectionkey. OP_accept);while (true) {int readychannels = Selector. Select();if (readychannels==0) {System. out. println("No Channel is ready!");Continue;}Set<SelectionKey> Selectedkeys = Selector. Selectedkeys();iterator<selectionkey> Keyiterator = Selectedkeys. Iterator();while (Keyiterator. Hasnext()) {Selectionkey key = Keyiterator. Next();if (key. Isacceptable()) {System. out. println("Receive operation!" ");}else if (key. Isconnectable()) {System. out. println("Connect operation!" ");}else if (key. IsReadable()) {System. out. println(Read the operation! ");}else if (key. iswritable()) {System. out. println("Write Operation!" ");} keyiterator. Remove();}        }    }}

The above code note that when registering an event can only be accept, other events outside the registration will cause the program to fail, because all the other events are registered after the accept, so pay attention to this point.

Next section: Waiting

"Java" "NiO" 7, 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.