netty4.0中EventExecutorGroup池中选择线程的方式

今天看源代码,发现netty4.0在生成EventExecutorLoopGroup(线程池)时,初始化EventExecutor(执行的线程)时,初始化一个eventExecutor的选择器


protected MultithreadEventExecutorGroup(int nThreads, ThreadFactory threadFactory, Object... args) {
        if (nThreads <= 0) {
            throw new IllegalArgumentException(String.format("nThreads: %d (expected: > 0)", nThreads));
        }

        if (threadFactory == null) {
            threadFactory = newDefaultThreadFactory();
        }

        children = new SingleThreadEventExecutor[nThreads];
       //这里是主要说明一下,根据初始化线程池的大小判断线程选择器是哪个,EventExecutorChooser是内部的接口,外部无法访问
        if (isPowerOfTwo(children.length)) {
            chooser = new PowerOfTwoEventExecutorChooser();
        } else {
            chooser = new GenericEventExecutorChooser();
        }

        for (int i = 0; i < nThreads; i ++) {
            boolean success = false;
            try {
                children[i] = newChild(threadFactory, 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) {
                            Thread.currentThread().interrupt();
                            break;
                        }
                    }
                }
            }
        }

private interface EventExecutorChooser {
        EventExecutor next();
    }
//当初如线程是2的平方时,用这个选择
    private final class PowerOfTwoEventExecutorChooser implements EventExecutorChooser {
        @Override
        public EventExecutor next() {
            return children[childIndex.getAndIncrement() & children.length - 1];
        }
    }
//除此之前的其他的线程选择
    private final class GenericEventExecutorChooser implements EventExecutorChooser {
        @Override
        public EventExecutor next() {
            return children[Math.abs(childIndex.getAndIncrement() % children.length)];
        }
    }
发现以上2个方法最后得到的结果都是一样的,按顺序选择children数组中的线程,不同之外就是如果是2的平方的形式,因为是按位运算,所以执行的效率上是非常快的。而其他的选择因为要进行除余运算,所以在效率上应该会差一点。

你可能感兴趣的:(java)