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次方以取模操作獲取
}
}