標籤:each int 父類 false 內容 cin about lte list
我們從架構的應用程式層面來分析,NioEventLoopGroup在netty中的使用。
這是我們需要配置的地方。
緊接著我們進入netty的運行中。ServerBootstrap.bind(PORT);
這是一個bind操作。我們來看一下NioEventLoopGroup在這個操作中的使用。
ChannelFuture regFuture = config().group().register(channel);
config()返回在ServerBootstrap中內部屬性:private final ServerBootstrapConfig config = new ServerBootstrapConfig(this);
注意這裡傳入的是this即ServerBootstrap對象。
這個類主要是用來暴露我們的配置的,直接把我們配置的ServerBootstrap傳遞進來。
我們繼續ChannelFuture regFuture = config().group().register(channel);
這裡的config()返回一個ServerBootstrapConfig,然後調用他的group()。
這個類是ServerBootstrapConfig的父類。調用了ServerBootstrap.group().方法。注意因為group方法是在弗雷AbstractBootstrap中定義的,所以這裡進入父類的group()方法中來。
這個方法直接返回EventLoopGroup對象。
我們在回過頭來看我們最初的配置,來發現這個group屬性究竟是什麼。
我們配置了兩個NioEventLoopGroup,一個一個線程的傳遞給了父類AbstractBootstrap.一個初始化給當前的ServerBootstrap的內部屬性childGroup.
我們在回到這裡ChannelFuture regFuture = config().group().register(channel);
現在通過AbstractBootstrap.group()方法返回了一個NioEventLoopGroup對象,即我們配置的第一個單線程的NioEventLoopGroup對象。
現在進入他的register(channel)方法。由於這個方法是在他的父類中定義的,所以我們進入他的父類MultithreadEventLoopGroup()中。
next()方法返回一個EventLoop對象。
下面重點分析這個chooser。(在=======以內,然後接著分析next()方法)
====================================================================
這個chooser是我們在初始化NioEventLoopGroup的時候初始化的。
回到我們初始化NioEventLoopGroup的地方:
還是這裡。
下面就到了初始化chooser的地方了:
/** * Create a new instance. * * @param nThreads the number of threads that will be used by this instance. * @param executor the Executor to use, or {@code null} if the default should be used. * @param chooserFactory the {@link EventExecutorChooserFactory} to use. * @param args arguments which will passed to each {@link #newChild(Executor, Object...)} call */ 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) { executor = new ThreadPerTaskExecutor(newDefaultThreadFactory()); } children = new EventExecutor[nThreads]; for (int i = 0; i < nThreads; i ++) { boolean success = false; try { 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; } } } } } 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); } Set<EventExecutor> childrenSet = new LinkedHashSet<EventExecutor>(children.length); Collections.addAll(childrenSet, children); readonlyChildren = Collections.unmodifiableSet(childrenSet); }
這個構造方法內容比較多。別的先不管,我們來看:chooser = chooserFactory.newChooser(children);
這個EventExecutorChooserFactory chooserFactory是我們上個構造方法中傳過來的:
this(nThreads, executor, DefaultEventExecutorChooserFactory.INSTANCE, args);
是一個DefaultEventExecutorChooserFactory.INSTANCE。
然後我們看他的newChooser(EventExecutor[] executors)方法。
@SuppressWarnings("unchecked") @Override public EventExecutorChooser newChooser(EventExecutor[] executors) { if (isPowerOfTwo(executors.length)) { return new PowerOfTwoEventExecutorChooser(executors); } else { return new GenericEventExecutorChooser(executors); } }
這裡有個判斷就是:判斷是否為2的次方。
private static boolean isPowerOfTwo(int val) { return (val & -val) == val;}
然後根據是否為2的次方分別進行兩個構造方法。分別實現了EventExecutorChooser的next()方法。
private static final class PowerOfTwoEventExecutorChooser implements EventExecutorChooser { private final AtomicInteger idx = new AtomicInteger(); private final EventExecutor[] executors; PowerOfTwoEventExecutorChooser(EventExecutor[] executors) { this.executors = executors; } @Override public EventExecutor next() { return executors[idx.getAndIncrement() & executors.length - 1]; } } private static final class GenericEventExecutorChooser implements EventExecutorChooser { private final AtomicInteger idx = new AtomicInteger(); private final EventExecutor[] executors; GenericEventExecutorChooser(EventExecutor[] executors) { this.executors = executors; } @Override public EventExecutor next() { return executors[Math.abs(idx.getAndIncrement() % executors.length)]; } }
這兩個實作類別只是對於next的方法有不同的實現。但是都是遍曆每一個executors。
為什麼要這樣呢?
原因是位操作& 比 % 操作要高效。netty為了提高效率也是拼了。
總的來說這個DefaultEventExecutorChooserFactory非常簡單,就上面這些內容。現在我們也知道了chooser是什麼了,就是一個時限了遍曆所有EventExecutor的next()方法的對象。功能非常簡單,只有一個方法next。遍曆每一個EventExecutor。
=====================================================================
Netty4 NioEventLoopGroup 解析