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次方以取模操作获取
}
}
网友评论