NOTE
Netty 3.x Source Analysis
1. Overview 2. Boss-array initialization 3. Worker-array initialization 4. Bind
This is a historical learning note and may contain outdated or incomplete understanding.
1. Overview
Create two thread pools: one for initializing the boss array and one for initializing the worker array.
2. Boss-Array Initialization
All bosses share the same thread pool.
- Use
Selector.opento open a selector. - Execute a
runmethod through the thread pool. This method is an infinite loop.- Set
wakeuptofalse. - Call
selector.selectand block until an event needs to be processed (a client connection). - Repeatedly take tasks from the task queue and execute them until the queue is empty. This method is also an infinite loop.
- Then process this selector.
- Set
Obtain all SelectionKey instances from the selector and iterate over them.
Take the channel corresponding to each key, randomly obtain a worker, and put a task into that worker’s task queue.
The task is to register the channel’s read event with the selector.
3. Worker-Array Initialization
All workers share the same thread pool.
- Use
Selector.opento open the selector pool. - Execute a
runmethod through the thread pool. This method is an infinite loop.- Set
wakeuptofalse. - Call
selector.select; return directly on timeout. - Repeatedly take tasks from the task queue and execute them until the queue is empty. This method is also an infinite loop.
- Then process this selector.
- Set
Obtain all SelectionKey instances from the selector and iterate over them.
Take the channel corresponding to each key, read the data, output it, and write it back to the client.
4. bind Operation
Use ServerSocketChannel.open to open a channel, configure it as non-blocking, and bind the address.
Randomly obtain a boss, turn the channel’s accept event into a task, and put that task into the boss’s task queue.
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub