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));
}