Java Socket: Java-NIO-Selector

Source: Internet
Author: User

The appearance of Selector greatly improves the efficiency of multiple Java sockets. When there is no NIO, multiple polling sockets are completed through read blocking. Even in non-blocking mode, we still need to use the system call when polling whether the socket is ready. The appearance of Selector handed over the ready selection to the operating system (the well-known selec function), separating the ready judgment from the read data not only greatly improves the performance, it also makes the code clearer. The selector part of Java NIO actually has three important classes. 1. Selector to complete the main selection function. Select (), and save the channel set registered to it. 2. The SelectableChannel can be registered to the channel on the Selector. 3. SelectionKey describes the relationship between a Selector and SelectableChannel. And save the operations that are of interest to the channel. Next, it is a general process. First, create a selector, then register the channel, and then select the ready channel to process the data of the ready channel. Let's use the code to see how these steps are completed. Java code Selector selector = Selector. open (); channel1.configureBlocking (false); channel2.configureBlocking (false); cahnnel3.configureBlocking (false); SelectionKey key1 = channel1.register (selector, SelectionKey. OP_READ); SelectionKey key2 = channel2.register (selector, SelectionKey. OP_WRITE | SelectionKey. OP_READ); SelectionKey key3 = channel3.register (selector, SelectionKey. OP_WRITE); while (true) {in T readyCount = selector. select (1000); if (readyCount = 0) continue; Iterator <SelectionKey> iter = selector. selectedKeys. iterator (); while (iter. hasNext () {SelectionKey key = iter. next (); if (key. isReadable () {readData (key);} iter. the above code is an example. We can see that creating a Selector using the open method is a static factory mode. Note that its exception handling is IOException. The following channels are not described. Generally, Socket channels are optional, but file channels are not optional. We can see that this channel calls methods such as configureBlocking (false). The channel should be non-blocking before it is registered to the Selector, otherwise the IllegalBlockingModeException will be thrown. Then we start to register the channel and use the registor method. The idea is followed by a parameter. If we register a write operation for a read-only channel, an IllegalArgumentException exception will be thrown. For example, SocketChannel does not support the accept operation. There are four types of operations: read, write, accept, and connect. Of course, we cannot register closed channels into Selector. If Selector calls close, most operations that attempt to access it will throw an exception. Next, we start to use the select function to update the selectedKey. This is complicated, but from the Code, after we finish the select function, we start to facilitate the selectedKey, locate the key that meets the requirements, and perform data read operations. Note that after the key is used, it must be deleted from the selectedKey set. The following is a more detailed description, because we still don't know how to update the selectedKey? First, a selectionKey contains two sets, one is a collection of registered operations of interest, and the other is a ready set. The first set is basically determined after registration, or changed through interestOps (int. Select does not change the interest set. However, the select statement changes the ready Set. This is the set of operations that interest you. In this case, the ready Set is actually a subset of the interest set. How to use these collections? Check the code: Java code if (key. readyOps () & SelectionKey. OP_READ )! = 0) {myBuffer. clear (); key. channel (). read (myBuffer); doSomething (myBuffer. flip ();} as shown in the code above, this set is only a mask, and operations are required to obtain the result. Of course, there are more convenient usage. If (key. isReadable () of the Java code, it should be noted that such a judgment is not necessarily, but a prompt. The underlying channel is changing at any time. For SelectionKey, you can also perform the cancel operation. A SelectionKey dropped by cancel is actually only stored in the Selector's cancel key set, and the key becomes invalid immediately, but the channel is still registered, the registration will not be canceled until the next select operation. Now let's take a look at what the selector has done. The selector is the core of the ready selection. It contains the Key of the channel and operation relationship registered to it. It maintains three sets. 1. Call a registered key set, keys () 2. Call a selected key set, selectedKeys () 3. Private Key set that has been canceled. Although the selector encapsulates select, poll, and other underlying system calls, it has its own set to manage these keys. When a select statement is called, she performs the following checks: 1. Checks the set of canceled keys. If it is not empty, remove the canceled key from the other two sets, cancel the related channel, and clear the set of canceled keys. 2. The interest set of keys in the set of registered keys is checked. For example, there is a new interest operation registration. However, this step will not affect subsequent operations. This is not affected until the next select call. After the prerequisites are confirmed, the underlying system performs a query. Parameters dependent on the select method. If the channel is not ready, the parameter timeout setting in the root select field may block the thread. After the system call is completed, you can perform the following operations on the channel of an operation in the ready interest set indicated by the operating system:: if the channel key is not in the selected key set, the ready Set of the key is cleared. Then, it indicates that the bit mask of the operations that have been prepared for the current channel discovered by the operating system will be set. B: otherwise, once the channel key is placed in the set of selected keys, the ready set is not cleared, but accumulated. That is to say, if the previous status is ready, this operation is no longer ready, but its bit still indicates ready and will not be cleared. 3. Step 2 may sleep for a long period of time. Therefore, after Step 2 is completed, step 1 continues to ensure that the canceled key is correctly processed. 4. return value. The return value of select indicates the number of ready options from the last call to the current call. If the last time is ready, no statistics will be collected this time. This is why we continue when the return value is 0. The latency logout method is used to solve the cancellation key issue. If the thread cancels the channel while canceling the key, it is likely to block and conflict with the ongoing selection operation. We can also select 1, select () 2, select (long timeout) 3, selectNow (); select () will block the thread and know that another channel is ready. Select with timeout will block at a specific time, or at least one channel is ready. If selectNow () is not found to be ready, it will be returned directly. How to stop interruption selection? There are three methods. 1. wakeup () is an elegant method and also a delay. If there is no ongoing selection operation, that is, it will not take effect until the next select operation. 2. If the close () selector is called, all threads that are blocked in the selection operation are awakened, the related channel is canceled, and the key is also canceled. 3. interrupt () actually interrupt will not interrupt the thread. Instead, it sets the thread interruption flag. Then we still call wakeup (). This is because Selector captures interruptedException, and then calls wakeup () in exception handling. Based on the above information, we can understand that the Selector actually performs operations on the set in the selection key, it is done by the programmer. It is critical to manage the selection key. The bit in the ready set is cumulative. According to step 2, if a key is in the selection set, the ready Set of this key will not be cleared. If this key is not in the selected set, you need to first clear the ready Set of this key, then update the ready information to this ready set, and finally, is to add this key to the selected set. This is why we need to delete the key to be processed in the above process, because if we do not delete it, the next information is accumulated, we cannot separate the operations in this select statement. If it is cleared, the ready set is the information updated After resetting if it is ready for the next time.

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.