成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

原理剖析(第 010 篇)Netty之服務(wù)端啟動(dòng)工作原理分析(上)

coordinate35 / 1341人閱讀

摘要:端引導(dǎo)類線程管理組線程管理組將設(shè)置到服務(wù)端引導(dǎo)類中指定通道類型為,一種異步模式,阻塞模式為設(shè)置讓服務(wù)器監(jiān)聽某個(gè)端口已等待客戶端連接。

原理剖析(第 010 篇)Netty之服務(wù)端啟動(dòng)工作原理分析(上)

-

一、大致介紹
1、Netty這個(gè)詞,對(duì)于熟悉并發(fā)的童鞋一點(diǎn)都不陌生,它是一個(gè)異步事件驅(qū)動(dòng)型的網(wǎng)絡(luò)通信框架;
2、使用Netty不需要我們關(guān)注過多NIO的API操作,簡簡單單的使用即可,非常方便,開發(fā)門檻較低;
3、而且Netty也經(jīng)歷了各大著名框架的“摧殘”,足以證明其性能高,穩(wěn)定性高;
4、那么本章節(jié)就來和大家分享分析一下Netty的服務(wù)端啟動(dòng)流程,分析Netty的源碼版本為:netty-netty-4.1.22.Final;
二、簡單認(rèn)識(shí)Netty 2.1 何為Netty?
1、是一個(gè)基于NIO的客戶端、服務(wù)器端的網(wǎng)絡(luò)通信框架;

2、是一個(gè)以提供異步的、事件驅(qū)動(dòng)型的網(wǎng)絡(luò)應(yīng)用工具;

3、可以供我們快速開發(fā)高性能的、高可靠性的網(wǎng)絡(luò)服務(wù)器與客戶端;
2.2 為什么使用Netty?
1、開箱即用,簡單操作,開發(fā)門檻低,API簡單,只需關(guān)注業(yè)務(wù)實(shí)現(xiàn)即可,不用關(guān)心如何編寫NIO;

2、自帶多種協(xié)議棧且預(yù)置多種編解碼功能,且定制化能力強(qiáng);

3、綜合性能高,已歷經(jīng)各大著名框架(RPC框架、消息中間件)等廣泛驗(yàn)證,健壯性非常強(qiáng)大;

4、相對(duì)于JDK的NIO來說,netty在底層做了很多優(yōu)化,將reactor線程的并發(fā)處理提到了極致;

5、社區(qū)相對(duì)較活躍,遇到問題可以隨時(shí)提問溝通并修復(fù);
2.3 大致闡述啟動(dòng)流程
1、創(chuàng)建兩個(gè)線程管理組,一個(gè)是bossGroup,一個(gè)是workerGroup,每個(gè)Group下都有一個(gè)線程組children[i]來執(zhí)行任務(wù);

2、bossGroup專門用來攬客的,就是接收客戶端的請(qǐng)求鏈接,而workerGroup專門用來干事的,bossGroup攬客完了就交給workerGroup去干活了;

3、通過bind輕松的一句代碼綁定注冊(cè),其實(shí)里面一點(diǎn)都不簡單,一堆堆的操作;

4、創(chuàng)建NioServerSocketChannel,并且將此注冊(cè)到bossGroup的子線程中的多路復(fù)用器上;

5、最后一步就是將NioServerSocketChannel綁定到指定ip、port即可,由此完成服務(wù)端的整個(gè)啟動(dòng)過程;
2.4 Netty服務(wù)端啟動(dòng)Demo
/**
 * Netty服務(wù)端啟動(dòng)代碼。
 *
 * @author hmilyylimh
 *
 * @version 0.0.1
 *
 * @date 2018/3/25
 *
 */
public class NettyServer {

    public static final int TCP_PORT = 20000;

    private final int port;

    public NettyServer(int port) {
        this.port = port;
    }

    public void start() throws Exception {
        EventLoopGroup bossGroup = null;
        EventLoopGroup workerGroup = null;
        try {
            // Server 端引導(dǎo)類
            ServerBootstrap serverBootstrap = new ServerBootstrap();

            // Boss 線程管理組
            bossGroup = new NioEventLoopGroup(1);

            // Worker 線程管理組
            workerGroup = new NioEventLoopGroup();

            // 將 Boss、Worker 設(shè)置到 ServerBootstrap 服務(wù)端引導(dǎo)類中
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    // 指定通道類型為NioServerSocketChannel,一種異步模式,OIO阻塞模式為OioServerSocketChannel
                    .localAddress("localhost", port)//設(shè)置InetSocketAddress讓服務(wù)器監(jiān)聽某個(gè)端口已等待客戶端連接。
                    .childHandler(new ChannelInitializer() {//設(shè)置childHandler執(zhí)行所有的連接請(qǐng)求
                        @Override
                        protected void initChannel(Channel ch) throws Exception {
                            ch.pipeline().addLast(new PacketHeadDecoder());
                            ch.pipeline().addLast(new PacketBodyDecoder());

                            ch.pipeline().addLast(new PacketHeadEncoder());
                            ch.pipeline().addLast(new PacketBodyEncoder());

                            ch.pipeline().addLast(new PacketHandler());
                        }
                    });
            // 最后綁定服務(wù)器等待直到綁定完成,調(diào)用sync()方法會(huì)阻塞直到服務(wù)器完成綁定,然后服務(wù)器等待通道關(guān)閉,因?yàn)槭褂胹ync(),所以關(guān)閉操作也會(huì)被阻塞。
            ChannelFuture channelFuture = serverBootstrap.bind().sync();
            System.out.println("Server started,port:" + channelFuture.channel().localAddress());
            channelFuture.channel().closeFuture().sync();
        } finally {
            // Shut down all event loops to terminate all threads.
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        new NettyServer(TCP_PORT).start();
    }
}
三、常用的類結(jié)構(gòu)

四、源碼分析Netty服務(wù)端啟動(dòng) 4.1、創(chuàng)建bossGroup對(duì)象
1、源碼:
    // NettyServer.java, Boss 線程管理組, 上面NettyServer.java中的示例代碼
    bossGroup = new NioEventLoopGroup(1);

    // NioEventLoopGroup.java
    /**
     * Create a new instance using the specified number of threads, {@link ThreadFactory} and the
     * {@link SelectorProvider} which is returned by {@link SelectorProvider#provider()}.
     */
    public NioEventLoopGroup(int nThreads) {
        this(nThreads, (Executor) null);
    }    
    
    // NioEventLoopGroup.java
    public NioEventLoopGroup(int nThreads, Executor executor) {
        this(nThreads, executor, SelectorProvider.provider());
    }    
    
    // NioEventLoopGroup.java
    public NioEventLoopGroup(
            int nThreads, Executor executor, final SelectorProvider selectorProvider) {
        this(nThreads, executor, selectorProvider, DefaultSelectStrategyFactory.INSTANCE);
    }    
    
    // NioEventLoopGroup.java
    public NioEventLoopGroup(int nThreads, Executor executor, final SelectorProvider selectorProvider,
                             final SelectStrategyFactory selectStrategyFactory) {
        super(nThreads, executor, selectorProvider, selectStrategyFactory, RejectedExecutionHandlers.reject());
    }    
    
    // MultithreadEventLoopGroup.java
    /**
     * @see MultithreadEventExecutorGroup#MultithreadEventExecutorGroup(int, Executor, Object...)
     */
    protected MultithreadEventLoopGroup(int nThreads, Executor executor, Object... args) {
        // DEFAULT_EVENT_LOOP_THREADS 默認(rèn)為CPU核數(shù)的2倍
        super(nThreads == 0 ? DEFAULT_EVENT_LOOP_THREADS : nThreads, executor, args);
    }    
    
    // MultithreadEventExecutorGroup.java
    /**
     * 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 args              arguments which will passed to each {@link #newChild(Executor, Object...)} call
     */
    protected MultithreadEventExecutorGroup(int nThreads, Executor executor, Object... args) {
        this(nThreads, executor, DefaultEventExecutorChooserFactory.INSTANCE, args);
    }    
    
    // MultithreadEventExecutorGroup.java
    /**
     * 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) { // 小于或等于零都會(huì)直接拋異常,由此可見,要想使用netty,還得必須至少得有1個(gè)線程跑起來才能使用
            throw new IllegalArgumentException(String.format("nThreads: %d (expected: > 0)", nThreads));
        }

        if (executor == null) { // 如果調(diào)用方不想自己定制線程池的話,那么則用netty自己默認(rèn)的線程池
            executor = new ThreadPerTaskExecutor(newDefaultThreadFactory());
        }

        children = new EventExecutor[nThreads]; // 構(gòu)建孩子結(jié)點(diǎn)數(shù)組,也就是構(gòu)建NioEventLoopGroup持有的線程數(shù)組

        for (int i = 0; i < nThreads; i ++) { // 循環(huán)線程數(shù),依次創(chuàng)建實(shí)例化線程封裝的對(duì)象NioEventLoop
            boolean success = false;
            try {
                children[i] = newChild(executor, args); // 最終調(diào)用到了NioEventLoopGroup類中的newChild方法
                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;
                        }
                    }
                }
            }
        }

        // 實(shí)例化選擇線程器,也就是說我們要想執(zhí)行任務(wù),對(duì)于nThreads個(gè)線程,我們得靠一個(gè)規(guī)則來如何選取哪個(gè)具體線程來執(zhí)行任務(wù);
        // 那么chooser就是來干這個(gè)事情的,它主要是幫我們選出需要執(zhí)行任務(wù)的線程封裝對(duì)象NioEventLoop
        chooser = chooserFactory.newChooser(children);

        final FutureListener terminationListener = new FutureListener() {
            @Override
            public void operationComplete(Future future) throws Exception {
                if (terminatedChildren.incrementAndGet() == children.length) {
                    terminationFuture.setSuccess(null);
                }
            }
        };

        for (EventExecutor e: children) {
            e.terminationFuture().addListener(terminationListener);
        }

        Set childrenSet = new LinkedHashSet(children.length);
        Collections.addAll(childrenSet, children);
        readonlyChildren = Collections.unmodifiableSet(childrenSet);
    }    
    
2、主要講述了NioEventLoopGroup對(duì)象的實(shí)例化過程,這僅僅只是講了一半,因?yàn)檫€有一半是實(shí)例化children[i]子線程組;

3、每個(gè)NioEventLoopGroup都配備了一個(gè)默認(rèn)的線程池executor對(duì)象,而且同時(shí)也配備了一個(gè)選擇線程器chooser對(duì)象;

4、每個(gè)NioEventLoopGroup都一個(gè)子線程組children[i],根據(jù)上層傳入的參數(shù)來決定子線程數(shù)量,默認(rèn)數(shù)量為CPU核數(shù)的2倍;
4.2、實(shí)例化線程管理組的孩子結(jié)點(diǎn)children[i]
1、源碼:
    // MultithreadEventExecutorGroup.java, 最終調(diào)用到了NioEventLoopGroup類中的newChild方法
    children[i] = newChild(executor, args);

    // NioEventLoopGroup.java
    @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]);
    }

    // NioEventLoop.java
    NioEventLoop(NioEventLoopGroup parent, Executor executor, SelectorProvider selectorProvider,
                 SelectStrategy strategy, RejectedExecutionHandler rejectedExecutionHandler) {
        // 調(diào)用父類的構(gòu)造方法
        // DEFAULT_MAX_PENDING_TASKS 任務(wù)隊(duì)列初始化容量值,默認(rèn)值為:Integer.MAX_VALUE
        // 若不想使用默認(rèn)值的話,那么就得自己配置 io.netty.eventLoop.maxPendingTasks 屬性值為自己想要的值
        super(parent, executor, false, DEFAULT_MAX_PENDING_TASKS, rejectedExecutionHandler);

        if (selectorProvider == null) {
            throw new NullPointerException("selectorProvider");
        }
        if (strategy == null) {
            throw new NullPointerException("selectStrategy");
        }

        // 這個(gè)對(duì)象在NioEventLoopGroup的構(gòu)造函數(shù)中通過SelectorProvider.provider()獲得,然后一路傳參到此類
        provider = selectorProvider;

        // 通過調(diào)用JDK底層類庫,為每個(gè)NioEventLoop配備一個(gè)多路復(fù)用器
        final SelectorTuple selectorTuple = openSelector();
        selector = selectorTuple.selector;
        unwrappedSelector = selectorTuple.unwrappedSelector;
        selectStrategy = strategy;
    }

    // SingleThreadEventLoop.java
    protected SingleThreadEventLoop(EventLoopGroup parent, Executor executor,
                                    boolean addTaskWakesUp, int maxPendingTasks,
                                    RejectedExecutionHandler rejectedExecutionHandler) {
        // 調(diào)用父類的構(gòu)造方法
        super(parent, executor, addTaskWakesUp, maxPendingTasks, rejectedExecutionHandler);

        // 構(gòu)造任務(wù)隊(duì)列,最終會(huì)調(diào)用NioEventLoop的newTaskQueue(int maxPendingTasks)方法
        tailTasks = newTaskQueue(maxPendingTasks);
    }

    // SingleThreadEventExecutor.java
    /**
     * Create a new instance
     *
     * @param parent            the {@link EventExecutorGroup} which is the parent of this instance and belongs to it
     * @param executor          the {@link Executor} which will be used for executing
     * @param addTaskWakesUp    {@code true} if and only if invocation of {@link #addTask(Runnable)} will wake up the
     *                          executor thread
     * @param maxPendingTasks   the maximum number of pending tasks before new tasks will be rejected.
     * @param rejectedHandler   the {@link RejectedExecutionHandler} to use.
     */
    protected SingleThreadEventExecutor(EventExecutorGroup parent, Executor executor,
                                        boolean addTaskWakesUp, int maxPendingTasks,
                                        RejectedExecutionHandler rejectedHandler) {
        // 調(diào)用父類的構(gòu)造方法
        super(parent);
        this.addTaskWakesUp = addTaskWakesUp; // 添加任務(wù)時(shí)是否需要喚醒多路復(fù)用器的阻塞狀態(tài)
        this.maxPendingTasks = Math.max(16, maxPendingTasks);
        this.executor = ObjectUtil.checkNotNull(executor, "executor");
        taskQueue = newTaskQueue(this.maxPendingTasks);
        rejectedExecutionHandler = ObjectUtil.checkNotNull(rejectedHandler, "rejectedHandler");
    }

    // AbstractScheduledEventExecutor.java
    protected AbstractScheduledEventExecutor(EventExecutorGroup parent) {
        // 調(diào)用父類的構(gòu)造方法
        super(parent);
    }

    // AbstractEventExecutor.java
    protected AbstractEventExecutor(EventExecutorGroup parent) {
        this.parent = parent;
    }



2、該流程主要實(shí)例化線程管理組的孩子結(jié)點(diǎn)children[i],孩子結(jié)點(diǎn)的類型為NioEventLoop類型;

3、仔細(xì)一看,netty的開發(fā)者對(duì)命名也很講究,線程管理組的類名為NioEventLoopGroup,線程管理組的子線程類名為NioEventLoop,
   有沒有發(fā)現(xiàn)有什么不一樣的地方?其實(shí)就是差了個(gè)Group幾個(gè)字母,線程管理組自然以Group結(jié)尾,不是組的就自然沒有Group字母;
   
4、每個(gè)NioEventLoop都持有組的線程池executor對(duì)象,方便添加task到任務(wù)隊(duì)列中;

5、每個(gè)NioEventLoop都有一個(gè)selector多路復(fù)用器,而那些Channel就是注冊(cè)到這個(gè)玩意上面的;

6、每個(gè)NioEventLoop都有一個(gè)任務(wù)隊(duì)列,而且這個(gè)隊(duì)列的初始化容器大小為1024;
4.3、如何構(gòu)建任務(wù)隊(duì)列
1、源碼:
    // SingleThreadEventLoop.java, 構(gòu)造任務(wù)隊(duì)列,最終會(huì)調(diào)用NioEventLoop的newTaskQueue(int maxPendingTasks)方法
    tailTasks = newTaskQueue(maxPendingTasks);

    // NioEventLoop.java
    @Override
    protected Queue newTaskQueue(int maxPendingTasks) {
        // This event loop never calls takeTask()
        // 由于默認(rèn)是沒有配置io.netty.eventLoop.maxPendingTasks屬性值的,所以maxPendingTasks默認(rèn)值為Integer.MAX_VALUE;
        // 那么最后配備的任務(wù)隊(duì)列的大小也就自然使用無參構(gòu)造隊(duì)列方法
        return maxPendingTasks == Integer.MAX_VALUE ? PlatformDependent.newMpscQueue()
                                                    : PlatformDependent.newMpscQueue(maxPendingTasks);
    }

    // PlatformDependent.java
    /**
     * Create a new {@link Queue} which is safe to use for multiple producers (different threads) and a single
     * consumer (one thread!).
     * @return A MPSC queue which may be unbounded.
     */
    public static  Queue newMpscQueue() {
        return Mpsc.newMpscQueue();
    }

    // Mpsc.java
    static  Queue newMpscQueue() {
        // 默認(rèn)值 MPSC_CHUNK_SIZE =  1024;
        return USE_MPSC_CHUNKED_ARRAY_QUEUE ? new MpscUnboundedArrayQueue(MPSC_CHUNK_SIZE)
                                            : new MpscUnboundedAtomicArrayQueue(MPSC_CHUNK_SIZE);
    }

2、這里主要看看NioEventLoop是如何構(gòu)建任務(wù)隊(duì)列的,而且還構(gòu)建了一個(gè)給定初始化容量值大小的隊(duì)列;
4.4、如何獲得多路復(fù)用器
1、源碼:
    // NioEventLoop.java, 通過調(diào)用JDK底層類庫,為每個(gè)NioEventLoop配備一個(gè)多路復(fù)用器
    final SelectorTuple selectorTuple = openSelector();
    selector = selectorTuple.selector;
    unwrappedSelector = selectorTuple.unwrappedSelector;
    selectStrategy = strategy;

    // NioEventLoop.java
    private SelectorTuple openSelector() {
        final Selector unwrappedSelector;
        try {
            // 通過 provider 調(diào)用底層獲取一個(gè)多路復(fù)用器對(duì)象
            unwrappedSelector = provider.openSelector();
        } catch (IOException e) {
            throw new ChannelException("failed to open a new selector", e);
        }

        // DISABLE_KEYSET_OPTIMIZATION: 是否優(yōu)化選擇器key集合,默認(rèn)為不優(yōu)化
        if (DISABLE_KEYSET_OPTIMIZATION) {
            return new SelectorTuple(unwrappedSelector);
        }

        // 執(zhí)行到此,說明需要優(yōu)化選擇器集合,首先創(chuàng)建一個(gè)選擇器集合
        final SelectedSelectionKeySet selectedKeySet = new SelectedSelectionKeySet();

        // 然后通過反射找到SelectorImpl對(duì)象
        Object maybeSelectorImplClass = AccessController.doPrivileged(new PrivilegedAction() {
            @Override
            public Object run() {
                try {
                    // 通過反射獲取SelectorImpl實(shí)現(xiàn)類對(duì)象
                    return Class.forName(
                            "sun.nio.ch.SelectorImpl",
                            false,
                            PlatformDependent.getSystemClassLoader());
                } catch (Throwable cause) {
                    return cause;
                }
            }
        });

        if (!(maybeSelectorImplClass instanceof Class) ||
                // ensure the current selector implementation is what we can instrument.
                !((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;

        // 以下run方法的主要目的就是將我們自己創(chuàng)建的selectedKeySet選擇器集合通過反射替換底層自帶的選擇器集合
        Object maybeException = AccessController.doPrivileged(new PrivilegedAction() {
            @Override
            public Object run() {
                try {
                    Field selectedKeysField = selectorImplClass.getDeclaredField("selectedKeys");
                    Field publicSelectedKeysField = selectorImplClass.getDeclaredField("publicSelectedKeys");

                    Throwable cause = ReflectionUtil.trySetAccessible(selectedKeysField, true);
                    if (cause != null) {
                        return cause;
                    }
                    cause = ReflectionUtil.trySetAccessible(publicSelectedKeysField, true);
                    if (cause != null) {
                        return cause;
                    }

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

        // 反射執(zhí)行完后,則將創(chuàng)建的selectedKeySet賦值為當(dāng)成員變量
        selectedKeys = selectedKeySet;
        logger.trace("instrumented a special java.util.Set into: {}", unwrappedSelector);
        return new SelectorTuple(unwrappedSelector,
                                 new SelectedSelectionKeySetSelector(unwrappedSelector, selectedKeySet));
    }

2、其實(shí)說獲得多路復(fù)用器,倒不如說多路復(fù)用器從何而來,是通過provider調(diào)用provider.openSelector()方法而獲得的;

3、而這個(gè)provider所產(chǎn)生的地方其內(nèi)部是一個(gè)靜態(tài)變量,細(xì)心的童鞋會(huì)發(fā)現(xiàn)SelectorProvider.provider()這個(gè)里面還真有一個(gè)靜態(tài)provider;

4、而這里給用戶做了一個(gè)選擇是否需要優(yōu)化選擇器,如果需要優(yōu)化則用自己創(chuàng)建的選擇器通過反射塞到底層的多路復(fù)用器對(duì)象中;
4.5、線程選擇器
1、源碼:
    // MultithreadEventExecutorGroup.java
    // 實(shí)例化選擇線程器,也就是說我們要想執(zhí)行任務(wù),對(duì)于nThreads個(gè)線程,我們得靠一個(gè)規(guī)則來如何選取哪個(gè)具體線程來執(zhí)行任務(wù);
    // 那么chooser就是來干這個(gè)事情的,它主要是幫我們選出需要執(zhí)行任務(wù)的線程封裝對(duì)象NioEventLoop
    chooser = chooserFactory.newChooser(children);    

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

    // PowerOfTwoEventExecutorChooser.java
    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];
        }
    }

    // GenericEventExecutorChooser.java
    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)];
        }
    }

2、記得在前面說過,在實(shí)例化線程組Group的時(shí)候,會(huì)實(shí)例化一個(gè)線程選擇器,而這個(gè)選擇器的實(shí)現(xiàn)方式也正是由通過線程數(shù)量來決定的;

3、PowerOfTwoEventExecutorChooser與GenericEventExecutorChooser的主要區(qū)別就是,當(dāng)線程個(gè)數(shù)為2的n次方的話,那么則用PowerOfTwoEventExecutorChooser實(shí)例化的選擇器;
   
4、因?yàn)镋ventExecutorChooser的next()方法,一個(gè)是與操作,一個(gè)是求余操作,而與操作的效率稍微高些,所以在選擇線程這個(gè)細(xì)小的差別,netty的開發(fā)人員也真實(shí)一絲不茍的處理;
4.6、未完待續(xù)...
由于篇幅過長難以發(fā)布,所以接下來的請(qǐng)看【原理剖析(第 011 篇)Netty之服務(wù)端啟動(dòng)工作原理分析(下)】

詳見 原理剖析(第 011 篇)Netty之服務(wù)端啟動(dòng)工作原理分析(下)

五、下載地址

https://gitee.com/ylimhhmily/SpringCloudTutorial.git

SpringCloudTutorial交流QQ群: 235322432

SpringCloudTutorial交流微信群: 微信溝通群二維碼圖片鏈接

歡迎關(guān)注,您的肯定是對(duì)我最大的支持!!!

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/71083.html

相關(guān)文章

  • 原理剖析 011 Netty服務(wù)端啟動(dòng)工作原理分析(下)

    摘要:原理剖析第篇之服務(wù)端啟動(dòng)工作原理分析下一大致介紹由于篇幅過長難以發(fā)布,所以本章節(jié)接著上一節(jié)來的,上一章節(jié)為原理剖析第篇之服務(wù)端啟動(dòng)工作原理分析上那么本章節(jié)就繼續(xù)分析的服務(wù)端啟動(dòng),分析的源碼版本為二三四章節(jié)請(qǐng)看上一章節(jié)詳見原理剖析第篇之 原理剖析(第 011 篇)Netty之服務(wù)端啟動(dòng)工作原理分析(下) - 一、大致介紹 1、由于篇幅過長難以發(fā)布,所以本章節(jié)接著上一節(jié)來的,上一章節(jié)為【原...

    Tikitoo 評(píng)論0 收藏0
  • #yyds干貨盤點(diǎn)#學(xué)不懂Netty?看不懂源碼?不存在的,這文章手把手帶你閱讀Netty源碼

    摘要:簡單來說就是把注冊(cè)的動(dòng)作異步化,當(dāng)異步執(zhí)行結(jié)束后會(huì)把執(zhí)行結(jié)果回填到中抽象類一般就是公共邏輯的處理,而這里的處理主要就是針對(duì)一些參數(shù)的判斷,判斷完了之后再調(diào)用方法。 閱讀這篇文章之前,建議先閱讀和這篇文章關(guān)聯(lián)的內(nèi)容。 1. 詳細(xì)剖析分布式微服務(wù)架構(gòu)下網(wǎng)絡(luò)通信的底層實(shí)現(xiàn)原理(圖解) 2. (年薪60W的技巧)工作了5年,你真的理解Netty以及為什么要用嗎?(深度干貨)...

    zsirfs 評(píng)論0 收藏0
  • 后端經(jīng)驗(yàn)

    摘要:在結(jié)構(gòu)上引入了頭結(jié)點(diǎn)和尾節(jié)點(diǎn),他們分別指向隊(duì)列的頭和尾,嘗試獲取鎖入隊(duì)服務(wù)教程在它提出十多年后的今天,已經(jīng)成為最重要的應(yīng)用技術(shù)之一。隨著編程經(jīng)驗(yàn)的日積月累,越來越感覺到了解虛擬機(jī)相關(guān)要領(lǐng)的重要性。 JVM 源碼分析之 Jstat 工具原理完全解讀 http://click.aliyun.com/m/8315/ JVM 源碼分析之 Jstat 工具原理完全解讀 http:...

    i_garfileo 評(píng)論0 收藏0
  • Java面試通關(guān)要點(diǎn)匯總集

    摘要:本文會(huì)以引出問題為主,后面有時(shí)間的話,筆者陸續(xù)會(huì)抽些重要的知識(shí)點(diǎn)進(jìn)行詳細(xì)的剖析與解答。敬請(qǐng)關(guān)注服務(wù)端思維微信公眾號(hào),獲取最新文章。 原文地址:梁桂釗的博客博客地址:http://blog.720ui.com 這里,筆者結(jié)合自己過往的面試經(jīng)驗(yàn),整理了一些核心的知識(shí)清單,幫助讀者更好地回顧與復(fù)習(xí) Java 服務(wù)端核心技術(shù)。本文會(huì)以引出問題為主,后面有時(shí)間的話,筆者陸續(xù)會(huì)抽些重要的知識(shí)點(diǎn)進(jìn)...

    gougoujiang 評(píng)論0 收藏0
  • 從小白程序員一路晉升為大廠高級(jí)技術(shù)專家我看過哪些書籍?(建議收藏)

    摘要:大家好,我是冰河有句話叫做投資啥都不如投資自己的回報(bào)率高。馬上就十一國慶假期了,給小伙伴們分享下,從小白程序員到大廠高級(jí)技術(shù)專家我看過哪些技術(shù)類書籍。 大家好,我是...

    sf_wangchong 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<