NioEventLoopGroup
我們先看下類圖
NioEventLoopGroup workGroup = new NioEventLoopGroup();
public NioEventLoopGroup() {
this(0);
}
public NioEventLoopGroup(int nThreads) {
this(nThreads, (Executor) null);
}
public NioEventLoopGroup(int nThreads, Executor executor) {
//executor默認爲null
//ServerSocketChannel 就是通過ServerSocketChannel.open()==》SelectorProvider.provider().openServerSocketChannel()創建的
this(nThreads, executor, SelectorProvider.provider());
}
public NioEventLoopGroup(
int nThreads, Executor executor, final SelectorProvider selectorProvider) {
//nThreads默認爲零
//executor默認爲null
//ServerSocketChannel 就是通過ServerSocketChannel.open()==》SelectorProvider.provider().openServerSocketChannel()創建的
//DefaultSelectStrategyFactory.INSTANCE===》new DefaultSelectStrategyFactory() 默認選擇策略工廠
this(nThreads, executor, selectorProvider, DefaultSelectStrategyFactory.INSTANCE);
}
public NioEventLoopGroup(int nThreads, Executor executor, final SelectorProvider selectorProvider,
final SelectStrategyFactory selectStrategyFactory) {
//nThreads默認爲零
//executor默認爲null
//ServerSocketChannel 就是通過ServerSocketChannel.open()==》SelectorProvider.provider().openServerSocketChannel()創建的
//DefaultSelectStrategyFactory.INSTANCE===》new DefaultSelectStrategyFactory()
//線程池的拒絕策略,是指當任務添加到線程池中被拒絕,而採取的處理措施。
// 當任務添加到線程池中之所以被拒絕,可能是由於:第一,線程池異常關閉。第二,任務數量超過線程池的最大限制。
//RejectedExecutionHandlers.reject() ===》 new RejectedExecutionHandler() ===>丟棄任務並拋出RejectedExecutionException異常。
super(nThreads, executor, selectorProvider, selectStrategyFactory, RejectedExecutionHandlers.reject());
}
protected MultithreadEventLoopGroup(int nThreads, Executor executor, Object... args) {
//nThreads默認爲零
//executor默認爲null
//SelectorProvider ServerSocketChannel就是通過ServerSocketChannel.open()==》SelectorProvider.provider().openServerSocketChannel()創建的
//DefaultSelectStrategyFactory.INSTANCE===》new DefaultSelectStrategyFactory()
//RejectedExecutionHandlers.reject() ===》 new RejectedExecutionHandler()
//nThreads如果不傳默認是0 如果是0的話 就獲取CPU核數的兩倍 DEFAULT_EVENT_LOOP_THREADS==CPU核數的兩倍
super(nThreads == 0 ? DEFAULT_EVENT_LOOP_THREADS : nThreads, executor, args);
}
protected MultithreadEventExecutorGroup(int nThreads, Executor executor, Object... args) {
//nThreads默認爲零 如果是0的話 就獲取CPU核數的兩倍 DEFAULT_EVENT_LOOP_THREADS==CPU核數的兩倍
//executor默認爲null
//SelectorProvider ServerSocketChannel就是通過ServerSocketChannel.open()==》SelectorProvider.provider().openServerSocketChannel()創建的
//DefaultSelectStrategyFactory.INSTANCE===》new DefaultSelectStrategyFactory()
//RejectedExecutionHandlers.reject() ===》 new RejectedExecutionHandler()
//DefaultEventExecutorChooserFactory.INSTANCE 默認事件執行選擇器工廠
this(nThreads, executor, DefaultEventExecutorChooserFactory.INSTANCE, args);
}
//nThreads如果不傳默認是0 如果是0的話 就獲取CPU核數的兩倍 DEFAULT_EVENT_LOOP_THREADS==CPU核數的兩倍
//executor默認爲null
//chooserFactory=new DefaultEventExecutorChooserFactory() 默認 事件執行策略工廠
//args參數如下
//SelectorProvider ServerSocketChannel就是通過ServerSocketChannel.open()==》SelectorProvider.provider().openServerSocketChannel()創建的
//DefaultSelectStrategyFactory.INSTANCE===》new DefaultSelectStrategyFactory()
//RejectedExecutionHandlers.reject() ===》 new RejectedExecutionHandler()
protected MultithreadEventExecutorGroup(int nThreads, Executor executor,
EventExecutorChooserFactory chooserFactory, Object... args) {
if (nThreads <= 0) {
throw new IllegalArgumentException(String.format("nThreads: %d (expected: > 0)", nThreads));
}
if (executor == null) {
//newDefaultThreadFactory()=線程工廠 專門創建線程的
//newDefaultThreadFactory()調用的是 MultithreadEventLoopGroup.newDefaultThreadFactory()
//最終創建的是DefaultThreadFactory,他實現了繼承自jdk的ThreadFactory
executor = new ThreadPerTaskExecutor(newDefaultThreadFactory());
}
//nThreads如果不傳默認是0 如果是0的話 就獲取CPU核數的兩倍 DEFAULT_EVENT_LOOP_THREADS==CPU核數的兩倍
children = new EventExecutor[nThreads];
for (int i = 0; i < nThreads; i ++) {
//出現異常標識
boolean success = false;
try {
//創建nThreads個nioEventLoop保存到children數組中
children[i] = newChild(executor, args);
success = true;
} catch (Exception e) {
// TODO: Think about if this is a good exception type
throw new IllegalStateException("failed to create a child event loop", e);
} finally {
//出現異常處理
if (!success) {
for (int j = 0; j < i; j ++) {
children[j].shutdownGracefully();
}
for (int j = 0; j < i; j ++) {
EventExecutor e = children[j];
try {
while (!e.isTerminated()) {
e.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS);
}
} catch (InterruptedException interrupted) {
// Let the caller handle the interruption.
Thread.currentThread().interrupt();
break;
}
}
}
}
}
//children是 new NioEventLoop() 的對象數組
//chooser=GenericEventExecutorChooser/PowerOfTwoEventExecutorChooser
chooser = chooserFactory.newChooser(children);
final FutureListener<Object> terminationListener = new FutureListener<Object>() {
@Override
public void operationComplete(Future<Object> future) throws Exception {
if (terminatedChildren.incrementAndGet() == children.length) {
terminationFuture.setSuccess(null);
}
}
};
for (EventExecutor e: children) {
e.terminationFuture().addListener(terminationListener);
}
//複製一份children 只讀的
Set<EventExecutor> childrenSet = new LinkedHashSet<EventExecutor>(children.length);
Collections.addAll(childrenSet, children);
readonlyChildren = Collections.unmodifiableSet(childrenSet);
}
下面我們看下children[i] = newChild(executor, args);
@Override
protected EventLoop newChild(Executor executor, Object... args) throws Exception {
//executor=new ThreadPerTaskExecutor(newDefaultThreadFactory());
//args參數如下
//SelectorProvider ServerSocketChannel就是通過ServerSocketChannel.open()==》SelectorProvider.provider().openServerSocketChannel()創建的
//DefaultSelectStrategyFactory.INSTANCE===》new DefaultSelectStrategyFactory()
//RejectedExecutionHandlers.reject() ===》 new RejectedExecutionHandler()
return new NioEventLoop(this, executor, (SelectorProvider) args[0],
((SelectStrategyFactory) args[1]).newSelectStrategy(), (RejectedExecutionHandler) args[2]);
}
下面進入NioEventLoop的構造方法
NioEventLoop(NioEventLoopGroup parent, Executor executor, SelectorProvider selectorProvider,
SelectStrategy strategy, RejectedExecutionHandler rejectedExecutionHandler) {
//NioEventLoopGroup.this
//executor=new ThreadPerTaskExecutor(newDefaultThreadFactory());
//SelectorProvider ServerSocketChannel就是通過ServerSocketChannel.open()==》SelectorProvider.provider().openServerSocketChannel()創建的
//strategy=DefaultSelectStrategyFactory.INSTANCE===》new DefaultSelectStrategyFactory()
//rejectedExecutionHandler=RejectedExecutionHandlers.reject() ===》 new RejectedExecutionHandler()
super(parent, executor, false, DEFAULT_MAX_PENDING_TASKS, rejectedExecutionHandler);
if (selectorProvider == null) {
throw new NullPointerException("selectorProvider");
}
if (strategy == null) {
throw new NullPointerException("selectStrategy");
}
//provider=SelectorProvider.provider()
provider = selectorProvider;
final SelectorTuple selectorTuple = openSelector();
//替換了數據結構selectedKeys publicSelectedKeys的原生selector
selector = selectorTuple.selector;
//子類包裝的selector 底層數據結構也是被替換了的
unwrappedSelector = selectorTuple.unwrappedSelector;
//selectStrategy=new DefaultSelectStrategyFactory()
selectStrategy = strategy;
}
下步進入super()
protected SingleThreadEventLoop(EventLoopGroup parent, Executor executor,
boolean addTaskWakesUp, int maxPendingTasks,
RejectedExecutionHandler rejectedExecutionHandler) {
//NioEventLoopGroup.this
//executor=new ThreadPerTaskExecutor(newDefaultThreadFactory());
// addTaskWakesUp=false
//maxPendingTasks=2147483647 默認最大掛起任務
//rejectedExecutionHandler ===》 new RejectedExecutionHandler()
super(parent, executor, addTaskWakesUp, maxPendingTasks, rejectedExecutionHandler);
//tailTasks=new LinkedBlockingQueue<Runnable>(maxPendingTasks);
tailTasks = newTaskQueue(maxPendingTasks);
}
protected Queue<Runnable> newTaskQueue(int maxPendingTasks) {
//創建一個無界的阻塞隊列
//LinkedBlockingQueue是一個使用鏈表完成隊列操作的阻塞隊列。鏈表是單向鏈表,而不是雙向鏈表。
// 採用對於的next構成鏈表的方式來存儲對象。由於讀只操作隊頭,而寫只操作隊尾,
return new LinkedBlockingQueue<Runnable>(maxPendingTasks);
}
protected SingleThreadEventExecutor(EventExecutorGroup parent, Executor executor,
boolean addTaskWakesUp, int maxPendingTasks,
RejectedExecutionHandler rejectedHandler) {
//NioEventLoopGroup.this
//executor=new ThreadPerTaskExecutor(new DefaultThreadFactory());
// addTaskWakesUp=false
//maxPendingTasks=2147483647
//rejectedExecutionHandler ===》 new RejectedExecutionHandler()
super(parent);
// addTaskWakesUp=false
this.addTaskWakesUp = addTaskWakesUp;
//2147483647
this.maxPendingTasks = Math.max(16, maxPendingTasks);
//executor=執行器
this.executor = ThreadExecutorMap.apply(executor, this);
//new LinkedBlockingQueue<Runnable>(2147483647);
taskQueue = newTaskQueue(this.maxPendingTasks);
//new RejectedExecutionHandler()
rejectedExecutionHandler = ObjectUtil.checkNotNull(rejectedHandler, "rejectedHandler");
}
下面看下openSelector()
//創建selector 並且將selector中的selectedKeys publicSelectedKeys 從set集合用數組替代
private SelectorTuple openSelector() {
final Selector unwrappedSelector;
try {
//調用nio api創建selector
unwrappedSelector = provider.openSelector();
} catch (IOException e) {
throw new ChannelException("failed to open a new selector", e);
}
// System.out.println(unwrappedSelector.getClass());
if (DISABLE_KEY_SET_OPTIMIZATION) {
//將selector保存到SelectorTuple
return new SelectorTuple(unwrappedSelector);
}
//加載SelectorImpl類 得到SelectorImpl的類類型
Object maybeSelectorImplClass = AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
return Class.forName(
"sun.nio.ch.SelectorImpl",
false,
PlatformDependent.getSystemClassLoader());
} catch (Throwable cause) {
return cause;
}
}
});
if (!(maybeSelectorImplClass instanceof Class) ||
// isAssignableFrom()方法是從類繼承的角度去判斷,instanceof關鍵字是從實例繼承的角度去判斷。
//isAssignableFrom()方法是判斷是否爲某個類的父類,instanceof關鍵字是判斷是否某個類的子類。
//使用方法 父類.class.isAssignableFrom(子類.class) 子類實例 instanceof 父類類型
!((Class<?>) maybeSelectorImplClass).isAssignableFrom(unwrappedSelector.getClass())) {
if (maybeSelectorImplClass instanceof Throwable) {
Throwable t = (Throwable) maybeSelectorImplClass;
logger.trace("failed to instrument a special java.util.Set into: {}", unwrappedSelector, t);
}
return new SelectorTuple(unwrappedSelector);
}
final Class<?> selectorImplClass = (Class<?>) maybeSelectorImplClass;
//netty自定義的Set
final SelectedSelectionKeySet selectedKeySet = new SelectedSelectionKeySet();
Object maybeException = AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
Field selectedKeysField = selectorImplClass.getDeclaredField("selectedKeys");
Field publicSelectedKeysField = selectorImplClass.getDeclaredField("publicSelectedKeys");
if (PlatformDependent.javaVersion() >= 9 && PlatformDependent.hasUnsafe()) {
// Let us try to use sun.misc.Unsafe to replace the SelectionKeySet.
// This allows us to also do this in Java9+ without any extra flags.
long selectedKeysFieldOffset = PlatformDependent.objectFieldOffset(selectedKeysField);
long publicSelectedKeysFieldOffset =
PlatformDependent.objectFieldOffset(publicSelectedKeysField);
if (selectedKeysFieldOffset != -1 && publicSelectedKeysFieldOffset != -1) {
PlatformDependent.putObject(
unwrappedSelector, selectedKeysFieldOffset, selectedKeySet);
PlatformDependent.putObject(
unwrappedSelector, publicSelectedKeysFieldOffset, selectedKeySet);
return null;
}
// We could not retrieve the offset, lets try reflection as last-resort.
}
Throwable cause = ReflectionUtil.trySetAccessible(selectedKeysField, true);
if (cause != null) {
return cause;
}
cause = ReflectionUtil.trySetAccessible(publicSelectedKeysField, true);
if (cause != null) {
return cause;
}
//替換SelectorImpl中原先使用的Set實現類
selectedKeysField.set(unwrappedSelector, selectedKeySet);
publicSelectedKeysField.set(unwrappedSelector, selectedKeySet);
return null;
} catch (NoSuchFieldException e) {
return e;
} catch (IllegalAccessException e) {
return e;
}
}
});
if (maybeException instanceof Exception) {
selectedKeys = null;
Exception e = (Exception) maybeException;
logger.trace("failed to instrument a special java.util.Set into: {}", unwrappedSelector, e);
return new SelectorTuple(unwrappedSelector);
}
selectedKeys = selectedKeySet;
logger.trace("instrumented a special java.util.Set into: {}", unwrappedSelector);
return new SelectorTuple(unwrappedSelector,
new SelectedSelectionKeySetSelector(unwrappedSelector, selectedKeySet));
}