Java NiO – channel and selector


Java NiO has three core components: buffer, channel and selector.

In the previous article, we introduced buffer. This article mainly introduces the remaining two components: channel and selector.

Java NiO - channel and selector


Channel means “channel” in translation. All Java NIOS must pass through channel. A channel object actually corresponds to an IO connection. Java NiO mainly includes the following channel implementations:

  • FileChannel
  • DatagramChannel
  • SocketChannel
  • ServerSocketChannel

It is used to process file IO, UDP, TCP client and TCP server respectively.

Here, take serversocketchannel and socketchannel as examples to introduce some common methods.

// server:

For the server, first useopenMethod to create an object, and then usebindMethod to bind the port.

After binding, useacceptMethod waits for a new connection to come in. This method is blocked. Once there is a new connection, the blocking will be released. Calling again blocks waiting for the next connection.

Used in conjunction with bufferreadMethod can read the data from the channel to the buffer, and then perform subsequent processing.

// Client:

There are some minor differences for the client. Client not requiredbindListen to the port, but directlyconnectTry to connect to the server.

It is also used with buffer and channelwriteMethod can write the data from the buffer to the channel, and then the subsequent network transmission can be done.


Selector is translated as “selector”, which allows one thread to process multiple channels. The application scenario of selector is: if your application opens multiple channels, but the traffic of each connection is very low. For example: chat server or HTTP server.

Using the selector is simple. useopenMethod to create a selector object, and then register the channel with the selector.

//Create a selector

It should be noted that it must be usedconfigureBlocking(false)Set the channel to non blocking mode, otherwise it will be thrownIllegalBlockingModeExceptionAbnormal.

ChannelregisterThere are two overloaded methods:

SelectionKey register(Selector sel, int ops) {
    return register(sel, ops, null);
SelectionKey register(Selector sel, int ops, Object att);

aboutopsParameter, that is, the selector should care about the event type of this channel. InSelectionKeyThere are several constants in the class:

  • OP_ Read can read data from the channel
  • OP_ Write can write data to the channel
  • OP_ Connect is connected to the server
  • OP_ Accept has a new connection

If you are interested in more than one event, use the or operator as follows:

int interestSet = SelectionKey.OP_READ | SelectionKey.OP_WRITE;

It should be noted that,Filechannel has only blocking mode, non blocking mode is not supported, so it has no register method!

Third parameterattyesattachmentThe abbreviation of represents that you can pass in an “attachment”. In the returnedSelectionKeyObject, you can get the following objects:

  • Channel(): get channel
  • Selector(): get selector
  • Attachment(): get attachment
  • Attach (obj): update attachments

In addition, there are some methods to judge the current state:

  • isReadable()
  • isWritable()
  • isConnectable()
  • isAcceptable()

Generally speaking, we rarely use a single selectionkey directly, but poll all selectionkeys from the selector, such as:

Java NiO - channel and selector

while ( > 0) {

The selector can return two selectionkey Collections:

  • Keys (): a collection of registered keys
  • Selectedkeys(): a collection of selected keys

Not all registered keys are still valid, and some may have been deletedcancel()Method is called. So generally speaking, we pollselectedKeys()method.

Complete sample code

The following is a complete server client Demo:


public class Server {


public class Client {

Author: official account XY’s technology circle


This work adoptsCC agreement, reprint must indicate the author and the link to this article

Recommended Today

The selector returned by ngrx store createselector performs one-step debugging of fetching logic

Test source code: import { Component } from ‘@angular/core’; import { createSelector } from ‘@ngrx/store’; export interface State { counter1: number; counter2: number; } export const selectCounter1 = (state: State) => state.counter1; export const selectCounter2 = (state: State) => state.counter2; export const selectTotal = createSelector( selectCounter1, selectCounter2, (counter1, counter2) => counter1 + counter2 ); // […]