为尽可能提升性能,Netty中有提到一个串行无锁化概念。
什么是串行无锁化?
NioEventLoop维护了一个任务队列,队列在创建NioEventLoop时被初始化,是用来实现串行无锁化的载体。
//SingleThreadEventExecutor类
this.taskQueue = this.newTaskQueue(this.maxPendingTasks);
//NioEventLoop类
protected Queue<Runnable> newTaskQueue(int maxPendingTasks) {
return maxPendingTasks == 2147483647 ? PlatformDependent.newMpscQueue() : PlatformDependent.newMpscQueue(maxPendingTasks);
}
NioEventLoop同时封装了一个线程,用来处理客户端的连接事件,读写事件,以及处理任务队列中的任务。NioEventLoop类继承关系图和源码定义处:
NioEventLoop继承SingleThreadEventLoop,SingleThreadEventLoop继承SingleThreadEventExecutor。其中这个线程在SingleThreadEventExecutor中定义:
private volatile Thread thread;
上面任务队列的实现就是调用inEventLoop()先通过thread来判断当前线程是否是创建NioEventLoop时绑定的线程,如果是就直接执行读写操作,如果不是就说明是其他线程,把读写操作封装成任务放在任务队列中。inEventLoop源码:
//AbstractEventExecutor类
public boolean inEventLoop(){
return this.inEventLoop(Thread.currentThread());
}
//SingleThreadEventExecutor
private volatile Thread thread;
public boolean inEventLoop(Thread thread){
//之前说过NioEventLoop封装的线程在SingleThreadEventExecutor内定义,并在创建的时候初始化。
return thread = this.thread
}
这样一次完整的工作流程就这样完成,然而这样设计CPU利用率其实并不高,并发程度不够。但这种设计是线程安全的,Netty线程间不需要做同步控制,Netty可以通过调整NIO线程池的线程参数,可以同时启动多个串行化的线程并行运行,这样性能就提升了。