Netty 的EventExecutorChooserFactory

EventExecutorChooserFactory比较简单,提供了一个方法:

EventExecutorChooser newChooser(EventExecutor[] executors);

就是传入EventExecutor数组,返回一个EventExecutorChooser选择器,EventExecutorChooser是EventExecutorChooserFactory的内部接口
EventExecutorChooser也只有一个方法:

EventExecutor next();

按照一定算法产生一个EventExecutor。

EventExecutorChooserFactory有一个实现DefaultEventExecutorChooserFactory,它有两个内部类PowerOfTowEventExecutorChooser和GenericEventExecutorChooser,都实现了EventExecutorChooser接口。DefaultEventExecutorChooserFactory的newChooser方法会根据传入数组是不是2的N次方,选择其中一个:


public EventExecutorChooser newChooser(EventExecutor[] executors) {

if (isPowerOfTwo(executors.length)) {

return new PowerOfTowEventExecutorChooser(executors);

} else {

return new GenericEventExecutorChooser(executors);

}

}

private static booleanisPowerOfTwo(intval) {

return(val & -val) == val;//位操作实现是否是2的N次方检验

}

private static final classPowerOfTowEventExecutorChooserimplementsEventExecutorChooser {

private finalAtomicIntegeridx=newAtomicInteger();

private finalEventExecutor[]executors;

PowerOfTowEventExecutorChooser(EventExecutor[] executors) {

this.executors= executors;

}

@Override

publicEventExecutor next() {

returnexecutors[idx.getAndIncrement() &executors.length-1];//2的N次方以位操作获取

}

}

private static final classGenericEventExecutorChooserimplementsEventExecutorChooser {
  private finalAtomicIntegeridx=newAtomicInteger();
  private finalEventExecutor[]executors;
  GenericEventExecutorChooser(EventExecutor[] executors) {
  this.executors= executors;
  }

@Override

publicEventExecutor next() {
  return executors[Math.abs(idx.getAndIncrement() %executors.length)];//非2的N次方以取模操作获取
}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容