Selector
- Java course
- Expert
- Lesson 15/46
- 5 min
Learn multi-channel management with Selector.
Multiplexing with Selector
A Selector lets a single thread watch many channels. Channels register with the selector through a SelectionKey; the select call waits for channels that are ready. This is known as multiplexing.
Example: a server can watch hundreds of client channels with a single Selector. Each channel is set to non-blocking mode and registered. When select returns, the keys of ready channels are processed. This is far more efficient than spawning a thread per client.
Non-blocking channels
To use a Selector the channel must be in non-blocking mode. channel.configureBlocking(false) does this. Then the channel is registered to a selector with register, along with which events to watch.
Example: channel.register(sel, SelectionKey.OP_READ) waits for the channel to be ready to read. When select returns, the channel is taken from the ready key and data is processed. A blocking channel cannot be registered, so setting the mode is mandatory.
Practice Open a Selector and print its state
Open a selector with Selector.open() and assign it to sel. Print the result of sel.isOpen() with System.out.println. Then close it with sel.close().
Starter code
// Open a Selector
// Print the state with isOpen
// Close itSample solution
import java.nio.channels.Selector;
public class SelectorDemo {
public static void main(String[] args) throws Exception {
Selector sel = Selector.open();
System.out.println(sel.isOpen());
sel.close();
}
}Expected output
true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the Selector.open call
Selector sel = Selector.____();
Selector sel = Selector.open();
Explanation: Selector.open creates a new selector.
2 Match the Selector concepts
| Term | Meaning |
|---|---|
Selector.open |
Opens a selector |
select |
Waits for an event |
isOpen |
Asks for state |
close |
Closes the selector |
3 What does a Selector provide?
- File deletion
- A single instance
- String encoding
- Many channels with one thread Correct answer
Explanation: A Selector watches many channels with one thread.