In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article will explain in detail what Selector is in Java NIO. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
1. Introduction to Selector 1. The relationship between Selector and Channel
Selector is commonly referred to as a selector and can be translated into multiplexing. It is one of the core components of Java NIO that checks whether the state of one or more NIO Channel (channels) is readable and writable. In this way, you can manage multiple Channels with a single thread, that is, you can manage multiple network links.
The advantage of using Selector is that you can handle the channel with fewer threads, avoiding the overhead of thread context switching compared to using multiple threads.
2. Selectable channel (SelectableChannel)
(1) not all Channel can be reused by Selector. For example, FileChannel cannot be reused by selectors. To judge that a Channel can be reused by Selector, there is a premise: to determine whether it inherits an abstract class SelectableChannel. If you inherit SelectableChannel, it can be reused, otherwise it cannot.
(2) SelectableChannel provides the public methods needed to achieve channel selectivity. It is the parent of all ready-to-check channel classes, and all socket channels inherit from the SelectableChannel class are optional, including channels obtained from the Pipe object. The FileChannel class, however, does not inherit SelectableChannel, so it is not an optional channel.
(3) A channel can be registered with multiple selectors, but only once for each selector. The relationship between the channel and the selector is accomplished by registration. SelectableChannel can be registered with the Selector object, and Selector is interested in the operations that need to specify the channel at the time of registration.
3. Channel registers with Selector
(1) when a channel is registered with a selector using the Channel.register (Selector sel, int pos) method. The first parameter specifies the selector to register for the channel. The second parameter specifies the channel operation that the selector needs to query.
(2) Channel operations that can be queried by selector are classified by type, including the following four types:
Readable: SelectionKey.OP_READ
Writable: SelectionKey.OP_WRITE
Connection: SelectionKey.OP_CONNECT
Receive: SelectionKey.OP_ACCEPT
If Selector is interested in the multi-operation type of the channel, you can use the "bit OR" operator to do this:
For example, int key = SelectionKey.OP_READ | SelectionKey.OP_WRITE
(3) the selector does not query the operation of the channel, but a ready state of an operation of the channel. The ready state of what operation? Once the channel has the conditions to complete an operation, it indicates that some operation of the channel is ready, it can be queried by Selector, and the program can operate on the channel accordingly. For example, if a SocketChannel channel can connect to a server, it is in the connection ready state (OP_CONNECT). For example, a ServerSocketChannel server channel that is ready to receive incoming connections is in the receive ready (OP_ACCEPT) state. For example, a data readable channel can be said to be "OP_READ". A channel waiting to write data can be said to be "OP_WRITE".
4. Select key (SelectionKey)
(1) after Channel registration, and once the channel is in a certain ready state, it can be queried by the selector. This is done using the select () method of the selector Selector. The function of the select method is to query the ready state of the channel operation of interest.
(2) Selector can constantly query the ready state of operations that occur in Channel. And choose the state of operational readiness that you are willing to go. Once the channel has an operation ready state and is of interest to Selecor, it will be selected by Selector and placed in the selection key collection.
(3) A select key that first contains the type of channel operation registered in Selector, such as SelectionKey.OP_READ. It also contains the registration relationship between a specific channel and a specific selector.
To develop an application, selecting keys is the key to programming, and NIO programming is more corresponding to selecting keys for different business logic processing.
(4) the concept of selection key is similar to the concept of event. A select key is similar to an event in listener mode. Because Selector is not an event-triggered mode, but an active query mode, it is not called an event Event, but a SelectionKey select key.
2. The method of using Selector 1. The creation of Selector
Create a Selector object through the Selector.open () method. As follows
/ / get Selector selector Selector selector = Selector.open (); 2. Register Channel to Selector
To implement Selector management Channel, you need to register the channel with the appropriate Selector
/ / 1. Get the Selector selector Selector selector = Selector.open (); / / 2. Get the channel ServerSocketChannel socketChannel = ServerSocketChannel.open (); / / 3. Set to non-blocking socketChannel.configureBlocking (false); / / 4. Bind connection socketChannel.bind (new InetSocketAddress (9999)); / / 5. Register the channel with the selector socketChannel.register (selector, SelectionKey.OP_ACCEPT)
The above registers it with a selector by calling the channel's register () method.
It is important to note that:
(1) when used with Selector, channel must be in non-blocking mode, otherwise an exception IllegalBlockingModeException will be thrown. This means that FileChannel cannot be used with Selector because FileChannel cannot switch to non-blocking mode, and all socket-related channels can.
(2) A channel does not necessarily have to hold all four operations. For example, the server channel ServerSocketChannel supports Accept receive operations, while the SocketChannel client channel does not. You can get the set of operations supported under a particular channel through the vildOps () method on the channel.
3. Rotation training query ready operation
(1) through the select () method of Selector, you can query the channel operations that are ready and some sets of ready states, which are contained in a Set collection whose elements are Selectionkey objects.
(2) here are several overloaded query select () methods of Selector:
Select () blocks until at least one channel is ready for the event you registered.
Select (long timeout) is the same as select (), but the longest blocking event is timeout milliseconds.
SelectNow () is non-blocking and returns as soon as there is a channel.
The int returned by the select () method indicates how many channels are ready. To be exact, the current select
Method comes to the time period between select methods, how many channels are programmed to be ready.
For example, when the select () method is called for the first time, 1 is returned if one channel is programmed to be ready, and if the select () method is called again, if the other channel is ready, it will return 1 again. If the first ready chnanel doesn't do anything, there are two ready channels now, but only one channel is ready between each select () method call.
Once the select () method is called and the value part 0 is returned, there is a seletedKeys () method in Selector that ranges the selected key set, iterates over each element of the set, and completes the corresponding operation according to the type of ready operation.
/ / query the channel operation Set selectedKeys = selector.selectedKeys (); Iterator iterator = selectedKeys.iterator (); while (iterator.hasNext ()) {SelectionKey key = iterator.next (); / / determine the key ready operation if (key.isAcceptable ()) {/ / a connection was accepted by a ServerSocketChannel. } else if (key.isConnectable ()) {/ / a connection was 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}} iterator.remove (); 4. Method to stop selection
The selector performs a summary of the selected process, and the bottom layer of the system asks whether each channel is ready in turn, which may cause the calling thread to enter a blocking state, so there are three ways to wake up the thread blocked in the select () method.
The wakeup () method: causes the blocked select () method to return immediately by calling the wakeup () method of the Selector object
This method causes the selection operation that the first hash on the selector does not return to return immediately. If there is no selection operation in progress, the next call to the select () method returns immediately.
Close () method: close selector through the close () method
This method wakes up any thread blocked during the selection operation (similar to wakeup ()), while all Channel registered with the Selector are logged out, all keys are canceled, but the Channel itself is not closed.
Sample code 1, server code @ Testpublic void server () throws IOException {/ / 1. Get the server channel ServerSocketChannel serverSocketChannel = ServerSocketChannel.open (); / / 2. Switch non-blocking mode serverSocketChannel.configureBlocking (false); / / 3. Create buffer ByteBuffer readBuffer = ByteBuffer.allocate (1024); ByteBuffer writeBuffer = ByteBuffer.allocate (1024); writeBuffer.put ("received." .getBytes (StandardCharsets.UTF_8); / / 4. Bind port number serverSocketChannel.bind (new InetSocketAddress (20000)); / / 5. Get the selector selector Selector selector = Selector.open (); / / 6. Register the channel to the selector to listen to serverSocketChannel.register (selector, SelectionKey.OP_ACCEPT); / / 7. Selector carries on the rotation training, carries on the subsequent operation while (selector.select () > 0) {Set selectionKeys = selector.selectedKeys (); Iterator selectionKeyIterator = selectionKeys.iterator (); / / Loop while (selectionKeyIterator.hasNext ()) {/ / get ready state SelectionKey k = selectionKeyIterator.next () / / Operation determines if (k.isAcceptable ()) {/ / get connection SocketChannel accept = serverSocketChannel.accept (); / / switch non-blocking mode accept.configureBlocking (false); / / register accept.register (selector, SelectionKey.OP_READ) } else if (k.isReadable ()) {SocketChannel socketChannel = (SocketChannel) k.channel (); readBuffer.clear (); socketChannel.read (readBuffer); readBuffer.flip (); System.out.println ("received:" + new String (readBuffer.array (), StandardCharsets.UTF_8)) K.interestOps (SelectionKey.OP_WRITE);} else if (k.isWritable ()) {writeBuffer.rewind (); SocketChannel socketChannel = (SocketChannel) k.channel (); socketChannel.write (writeBuffer); k.interestOps (SelectionKey.OP_READ) } 2, client code @ Testpublic void client () throws IOException {/ / 1. Get the channel, bind the host and port number SocketChannel socketChannel = SocketChannel.open (new InetSocketAddress (20000)); / / 2. Switch to non-blocking mode socketChannel.configureBlocking (false); / / 3. Create buffer ByteBuffer buffer = ByteBuffer.allocate (1024); / / 4. Write buffer data buffer.put (new Date (). ToString (). GetBytes (StandardCharsets.UTF_8)); / / 5. Mode switch buffer.flip (); / / 6. Write channel socketChannel.write (buffer); / / 7. Close buffer.clear (); socketChannel.close ();} 3. Summary of NIO programming steps
1. Create a ServerSocketChannel channel
2. Set to non-blocking mode
3. Create a Selector selector
4. Channel registers in the selector to listen for connection events
5. Call the select method (circular call) in Selector to listen for whether the channel is ready.
6. You can get the ready channel collection by calling the SelectKeys () method
7. Traverse the ready channel collection, determine the type of ready event, and implement specific business operations.
8. According to the business process, judge whether it is necessary to register the event monitoring event again and execute it repeatedly.
This is the end of this article on "what is Selector in Java NIO?". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.