Using a selector
A selector is used in an NIO application and allows one thread to handle multiple channels. The selector coordinates multiple channels and their events. It identifies those channels that are ready for processing. If we were to use a thread per channel, then we will find ourselves switching between threads frequently. This switching process can be expensive. Using a single thread to handle multiple channels avoids some of this overhead.
The following figure depicts this architecture. A thread is registered with a selector. The selector will identify the channels and events that are ready for processing.
A selector is supported by two primary classes:
Selector
: This provides the primary functionalitySelectionKey
: This identifies the types of events that are ready for processing
To use a selector, perform the following actions:
Create a selector
Register channels with the selector
Select a channel for use when it becomes available
Let's examine each of these steps in more detail...