Netty服务端源码阅读笔记(二)new NioEventLoopGroup

16 篇文章 0 订阅

NioEventLoopGroup中有一个数组来存放NioEventLoop,执行execute()方法时,调用next()方法使用EventExecutorChooser对象来选择某一个NioEventLoop来处理任务

继承关系

NioEventLoopGroup是NioEventLoop的池,以我的理解来理解源码的话,需要先大概了解他们间的关系,因此先来看NioEventLoopGroup的继承关系

顶层接口Executor就是juc包中的执行器接口,只有一个方法execute(Runnable command)

重点就是NioEventLoopGroup的execute、next、shutdownGracefully、register方法,这里暂时只看execute,其他的在之后代码中会看到

直接来看NioEventLoopGroup的execute方法

NioEventLoopGroup.execute()

调用了父类execute方法

public abstract class AbstractEventExecutorGroup implements EventExecutorGroup { 
  @Override
    public void execute(Runnable command) {
        next().execute(command);
    }
}

next()实现在AbstractEventExecutorGroup子类MultithreadEventExecutorGroup 

public abstract class MultithreadEventExecutorGroup extends AbstractEventExecutorGroup {
  
 private final EventExecutorChooserFactory.EventExecutorChooser chooser;   
 @Override
    public EventExecutor next() {
        return chooser.next();
    }
}

NioEventLoopGroup是NioEventLoop的池,那这个next()应该是选择NioEventLoop的方法,NioEventLoop也实现了Executor接口,选出来一个NioEventLoop执行它的execute方法,大概了解这些以后来看new

new NioEventLoopGroup()

// new方法跟ThreadPoolExecutor线程池一样,很多的参数,也提供默认选择
public class NioEventLoopGroup extends MultithreadEventLoopGroup {

     
    public NioEventLoopGroup() {
        this(0);
    }

    public NioEventLoopGroup(int nThreads) {
        this(nThreads, (Executor) null);
    }

    public NioEventLoopGroup(int nThreads, ThreadFactory threadFactory) {
        this(nThreads, threadFactory, SelectorProvider.provider());
    }

    public NioEventLoopGroup(int nThreads, Executor executor) {
        this(nThreads, executor, SelectorProvider.provider());
    }

    public NioEventLoopGroup(
            int nThreads, ThreadFactory threadFactory, final SelectorProvider selectorProvider) {
        this(nThreads, threadFactory, selectorProvider, DefaultSelectStrategyFactory.INSTANCE);
    }

    public NioEventLoopGroup(int nThreads, ThreadFactory threadFactory,
        final SelectorProvider selectorProvider, final SelectStrategyFactory selectStrategyFactory) {
        super(nThreads, threadFactory, selectorProvider, selectStrategyFactory, RejectedExecutionHandlers.reject());
    }

    public NioEventLoopGroup(
            int nThreads, Executor executor, final SelectorProvider selectorProvider) {
        this(nThreads, executor, selectorProvider, DefaultSelectStrategyFactory.INSTANCE);
    }

    public NioEventLoopGroup(int nThreads, Executor executor, final SelectorProvider selectorProvider,
                             final SelectStrategyFactory selectStrategyFactory) {
        super(nThreads, executor, selectorProvider, selectStrategyFactory, RejectedExecutionHandlers.reject());
    }

    public NioEventLoopGroup(int nThreads, Executor executor, EventExecutorChooserFactory chooserFactory,
                             final SelectorProvider selectorProvider,
                             final SelectStrategyFactory selectStrategyFactory) {
        super(nThreads, executor, chooserFactory, selectorProvider, selectStrategyFactory,
                RejectedExecutionHandlers.reject());
    }

    public NioEventLoopGroup(int nThreads, Executor executor, EventExecutorChooserFactory chooserFactory,
                             final SelectorProvider selectorProvider,
                             final SelectStrategyFactory selectStrategyFactory,
                             final RejectedExecutionHandler rejectedExecutionHandler) {
        super(nThreads, executor, chooserFactory, selectorProvider, selectStrategyFactory, rejectedExecutionHandler);
    }

}

各种构造函数参数含义 

SelectorProvider

nio编程中代码ServerSocketChannel.open();以及Selector.open();底层都是调用SelectorProvider.provider().openSelector();来实现

  public static SelectorProvider provider() {
        synchronized (lock) {
            if (provider != null)
                return provider;
            return AccessController.doPrivileged(
                new PrivilegedAction<SelectorProvider>() {
                    public SelectorProvider run() {
                            if (loadProviderFromProperty())
                                return provider;
                            if (loadProviderAsService())
                                return provider;
                            provider = sun.nio.ch.DefaultSelectorProvider.create();
                            return provider;
                        }
                    });
        }
    }

SelectStrategyFactory

默认 DefaultSelectStrategyFactory,选择策略DefaultSelectStrategy,如何选择就绪io事件,在NIO中就是selector.select()/selector.selectNow(),后期会看到

ThreadFactory

默认 new DefaultThreadFactory(getClass());   线程工厂new Thread()用的,里边有些许特殊操作,不是重点先不管

EventExecutorChooserFactory

默认new DefaultEventExecutorChooserFactory();  group中有多个EventLoop,在操作时会调用Chooser来选择一个EventLoop,这个就是Chooser工厂,分了两种实现类

public final class DefaultEventExecutorChooserFactory implements EventExecutorChooserFactory {
  
    private DefaultEventExecutorChooserFactory() { }

    @SuppressWarnings("unchecked")
    @Override
    public EventExecutorChooser newChooser(EventExecutor[] executors) {
        if (isPowerOfTwo(executors.length)) {
            return new PowerOfTwoEventExecutorChooser(executors);
        } else {
            return new GenericEventExecutorChooser(executors);
        }
    }

    // 小知识,负数二进制表示 == 正数的补码,对于2的幂来说,(val & -val) == val
    private static boolean isPowerOfTwo(int val) {
        return (val & -val) == val;
    }
}

两个实现类作用都是从一个EventExecutor数组中选择一个,区别是数组如果是2的幂,使用位运算计算(a % 8 == a & 7)

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

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

RejectedExecutionHandlers,拒绝策略,默认报错拒绝,之后代码在catch(Exception) 中会调用

   private static final RejectedExecutionHandler REJECT = new RejectedExecutionHandler() {
        @Override
        public void rejected(Runnable task, SingleThreadEventExecutor executor) {
            throw new RejectedExecutionException();
        }
    };
一直顺着无参构造方法点下去,线程个数为0,默认线程数取 当前机器处理器的核数(逻辑处理器) * 2
   private static final int DEFAULT_EVENT_LOOP_THREADS;

    static {
        // 默认线程数是 当前机器处理器的核数 * 2
        DEFAULT_EVENT_LOOP_THREADS = Math.max(1, SystemPropertyUtil.getInt(
                "io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2));

    } 

   protected MultithreadEventLoopGroup(int nThreads, Executor executor, Object... args) {
        super(nThreads == 0 ? DEFAULT_EVENT_LOOP_THREADS : nThreads, executor, args);
    }
public abstract class MultithreadEventExecutorGroup extends AbstractEventExecutorGroup {

    private final EventExecutor[] children;// 本文中就是nioEventLoop数组
    private final Set<EventExecutor> readonlyChildren;
    private final AtomicInteger terminatedChildren = new AtomicInteger();
    private final Promise<?> terminationFuture = new DefaultPromise(GlobalEventExecutor.INSTANCE);
    private final EventExecutorChooserFactory.EventExecutorChooser chooser;
 
   protected MultithreadEventExecutorGroup(int nThreads, Executor executor,
                                            EventExecutorChooserFactory chooserFactory, Object... args) {
        if (nThreads <= 0) {
            throw new IllegalArgumentException(String.format("nThreads: %d (expected: > 0)", nThreads));
        }

        // 没有传入executor ,默认一个执行器
        // newDefaultThreadFactory(), 默认的线程工厂
        // ThreadPerTaskExecutor实现Executor接口, public void execute(Runnable command){threadFactory.newThread(command).start();}
        if (executor == null) {
            executor = new ThreadPerTaskExecutor(newDefaultThreadFactory());
        }

        // 初始化NioEventLoop数组
        children = new EventExecutor[nThreads];

        for (int i = 0; i < nThreads; i ++) {
            boolean success = false;
            try {
                // newChild来实例化数组中每个EventExecutor对象,本文中为NioEventLoop对象
                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工厂根据EventExecutor的数量获取一个选择器
        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);
                }
            }
        };

        // private final Promise<?> terminationFuture = new DefaultPromise<Void>(GlobalEventExecutor.INSTANCE);
        // 异步返回结果的封装,为DefaultPromise加上一个监听器,当操作完成时更新DefaultPromise中的标志位
        for (EventExecutor e: children) {
            e.terminationFuture().addListener(terminationListener);
        }

        // 只读集合,用来干啥不知道
        Set<EventExecutor> childrenSet = new LinkedHashSet<EventExecutor>(children.length);
        Collections.addAll(childrenSet, children);
        readonlyChildren = Collections.unmodifiableSet(childrenSet);
    }
}

io.netty.channel.nio.NioEventLoopGroup#newChild

    @Override
    protected EventLoop newChild(Executor executor, Object... args) throws Exception {
        return new NioEventLoop(this, executor, (SelectorProvider) args[0],
            ((SelectStrategyFactory) args[1]).newSelectStrategy(), (RejectedExecutionHandler) args[2]);
    }

下节 Netty服务端源码阅读笔记(三)new NioEventLoop(1)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值