NIO SelectionKey readyOps bitmask pattern¶
The NIO SelectionKey readyOps bitmask pattern refers to the mechanism used in Java NIO to represent the I/O operation readiness state of a channel. The readyOps() method of a SelectionKey returns an integer representing a bitmask, where specific bits correspond to operation categories like read, write, connect, or accept^[600-developer-big-data-netty-netty-01.md].
This design allows for efficient state checking using bitwise operations.
Bitmask Values¶
The standard NIO operation constants correspond to specific bit positions (powers of two)^[600-developer-big-data-netty-netty-01.md]:
OP_READ:1 << 0(Value: 1)OP_WRITE:1 << 2(Value: 4)OP_CONNECT:1 << 3(Value: 8)OP_ACCEPT:1 << 4(Value: 16)
State Verification Logic¶
To determine if a channel is ready for a specific operation, a bitwise AND operation is performed between the readyOps() result and the operation constant^[600-developer-big-data-netty-netty-01.md].
The operation is considered ready if the result is non-zero:
if ((readyOps() & OP_READ) != 0) {
// Channel is ready for reading
}
If a channel's ready state is 4 (as in the example code), only OP_WRITE returns true, while checks for OP_READ, OP_CONNECT, and OP_ACCEPT return false^[600-developer-big-data-netty-netty-01.md].
Initialization¶
The ready set is initialized to zero when the SelectionKey is created^[600-developer-big-data-netty-netty-01.md].
It is subsequently updated by the Selector during selection operations and cannot be updated directly^[600-developer-big-data-netty-netty-01.md].
Related Concepts¶
- [[Netty]]
- [[Java NIO]]
Sources¶
^[600-developer-big-data-netty-netty-01.md]