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

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容