tomcat 8.x NioEndpoint之Acceptor組件淺析2

簡書 杭州_mina

tomcat 8.x NioEndpoint核心組件淺析1

1. Acceptor 淺析

   /**
     * The background thread that listens for incoming TCP/IP connections and
     * hands them off to an appropriate processor.
     */
    protected class Acceptor extends AbstractEndpoint.Acceptor {

        @Override
        public void run() {

            int errorDelay = 0;

            // Loop until we receive a shutdown command
            // 一直循環直到接收到關閉命令
            while (running) {

                // paused 只有在unbind的時候會設置
                while (paused && running) {
                    //變更Acceptor的狀態
                    state = AcceptorState.PAUSED;
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        // Ignore
                    }
                }
                
                if (!running) {
                    break;
                }
                // Acceptor 設置成running 
                state = AcceptorState.RUNNING;

                try {
                    //if we have reached max connections, wait
                    //連接數達到最大,暫停線程。
                    //這里用到的是connectionLimitLatch鎖,可以理解為一個閉鎖
                    //我理解connectionLimitLatch和coundownlatch類似
                    //補充一點這個是先增加計數器、如果超過最大連接數則減少計時器、然后線程暫停,你這個計時器就是當前連接數
                    //程序的下面我會簡單的講一下這個方法的實現
                    countUpOrAwaitConnection();

                    SocketChannel socket = null;
                    try {
                        // Accept the next incoming connection from the server
                        // socket
                        //調用serversocket的accept方法
                        socket = serverSock.accept();
                    } catch (IOException ioe) {
                        // We didn't get a socket
                        // 出錯了要減去連接數
                        countDownConnection();
                        if (running) {
                            // Introduce delay if necessary
                            errorDelay = handleExceptionWithDelay(errorDelay);
                            // re-throw
                            throw ioe;
                        } else {
                            break;
                        }
                    }
                    // Successful accept, reset the error delay
                    errorDelay = 0;

                    // Configure the socket
                    if (running && !paused) {
                        // setSocketOptions() will hand the socket off to
                        // an appropriate processor if successful
                        // 把socket扔到poller中
                        if (!setSocketOptions(socket)) {
                            // 如果加入poller失敗關閉連接
                            closeSocket(socket);
                        }
                    } else {
                        closeSocket(socket);
                    }
                } catch (Throwable t) {
                    ExceptionUtils.handleThrowable(t);
                    log.error(sm.getString("endpoint.accept.fail"), t);
                }
            }
            state = AcceptorState.ENDED;
        }
    }

下面來看setSocketOptions方法中如何把SocketChannel加入到poller中

protected boolean setSocketOptions(SocketChannel socket) {
        // Process the connection
        try {
            //disable blocking, APR style, we are gonna be polling it
            socket.configureBlocking(false); //設置成非阻塞
            //獲取socket
            Socket sock = socket.socket();
           //配置socket信息
            socketProperties.setProperties(sock);
            //創建一個NioChannel 他封裝了SocketChannel
            NioChannel channel = nioChannels.pop();
            if (channel == null) {
                //如果為null 創建一個NioChannel 這里使用系統內存
               //使用系統內存可以省去一步從系統內存拷貝到堆內存的動作、性能上會有很大的提升,nioChannels初始化默認為128個 
               //當socket 關閉的重新清理NioChannel而不是銷毀這個對象可以達到對象復用的效果、因為申請系統內存的開銷比申請堆內存的開銷要大很多
                SocketBufferHandler bufhandler = new SocketBufferHandler(
                        socketProperties.getAppReadBufSize(),
                        socketProperties.getAppWriteBufSize(),
                        socketProperties.getDirectBuffer());
                if (isSSLEnabled()) {
                    channel = new SecureNioChannel(socket, bufhandler, selectorPool, this);
                } else {
                    channel = new NioChannel(socket, bufhandler);
                }
            } else {
                //如果不為null設置SocketChannel
                channel.setIOChannel(socket);
                //將channle復位 以上就是重置系統內存把指針重新定位到buff的開始位置
                channel.reset();
            }
            //丟入poller隊列中
            getPoller0().register(channel);
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
            try {
                log.error("",t);
            } catch (Throwable tt) {
                ExceptionUtils.handleThrowable(tt);
            }
            // Tell to close the socket
            return false;
        }
        return true;
    }

最后一步register方法

 public void register(final NioChannel socket) {
             //設置poller 對象
            socket.setPoller(this); 
            //設置一個附件待會把這個NioSocketWrapper注冊到poller對象中的selector上去           
            NioSocketWrapper ka = new NioSocketWrapper(socket, NioEndpoint.this);//獲取
            socket.setSocketWrapper(ka);
            ka.setPoller(this);
            ka.setReadTimeout(getSocketProperties().getSoTimeout());
            ka.setWriteTimeout(getSocketProperties().getSoTimeout());
            ka.setKeepAliveLeft(NioEndpoint.this.getMaxKeepAliveRequests());
            ka.setSecure(isSSLEnabled());
            ka.setReadTimeout(getSoTimeout());
            ka.setWriteTimeout(getSoTimeout());
            PollerEvent r = eventCache.pop();
            ka.interestOps(SelectionKey.OP_READ);//this is what OP_REGISTER turns into.
            //生成一個PollerEvent對象 這個對象繼承了Runnable
            //這個對象的主要作用就是把NioSocketWrapper注冊到poller對象中的selector上去           
            //還有就是獲取SelectionKey 該對象是用于跟蹤這些被注冊事件的句柄
            if ( r==null) r = new PollerEvent(socket,ka,OP_REGISTER);
            else r.reset(socket,ka,OP_REGISTER);
            //把pollerEvent放入到poller的隊列中
           addEvent(r);
        }

2. LimitLatch 淺析

  • 2.1 AbstractEndpoint 封裝了LimitLatch一些方法
    //默認最大連接數為10000
    private int maxConnections = 10000;
    //獲取最大連接數
    public int  getMaxConnections() {
        return this.maxConnections;
    }
    //初始化閉鎖
    protected LimitLatch initializeConnectionLatch() {
        if (maxConnections==-1) return null;
        if (connectionLimitLatch==null) {
            //
            connectionLimitLatch = new LimitLatch(getMaxConnections());
        }
        return connectionLimitLatch;
    }
    //將會釋放所有的線程
    protected void releaseConnectionLatch() {
        LimitLatch latch = connectionLimitLatch;
        if (latch!=null) latch.releaseAll();
        connectionLimitLatch = null;
    }
    //增加計數,如果太大,那么等待
    protected void countUpOrAwaitConnection() throws InterruptedException {
        if (maxConnections==-1) return;
        LimitLatch latch = connectionLimitLatch;
        if (latch!=null) latch.countUpOrAwait();
    }
    //減少計數
    protected long countDownConnection() {
        if (maxConnections==-1) return -1;
        LimitLatch latch = connectionLimitLatch;
        if (latch!=null) {
            long result = latch.countDown();
            if (result<0) {
                getLog().warn(sm.getString("endpoint.warn.incorrectConnectionCount"));
            }
            return result;
        } else return -1
    }
  • 2.2 LimitLatch 源碼淺析
/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.apache.tomcat.util.threads;

import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;

import java.util.Collection;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * Shared latch that allows the latch to be acquired a limited number of times
 * after which all subsequent requests to acquire the latch will be placed in a
 * FIFO queue until one of the shares is returned.
 */
public class LimitLatch {

    private static final Log log = LogFactory.getLog(LimitLatch.class);
     //構建sync對象、主要用來同步、阻塞兩個功能
    private class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = 1L;

        public Sync() {
        }
        @Override
        protected int tryAcquireShared(int ignored) {
             //增加計數器
            long newCount = count.incrementAndGet();
            //如果計數器大于最大limit 則計數器減一 返回-1 否則返回 1 
            //這里的limit 其實就是maxConnections
            if (!released && newCount > limit) {
                // Limit exceeded
                count.decrementAndGet();
                return -1;
            } else {
                return 1;
            }
        }

        @Override
        protected boolean tryReleaseShared(int arg) {
            //計數器減一
            count.decrementAndGet();
            return true;
        }
    }

    private final Sync sync;
    //計數器
    private final AtomicLong count;
    //最大連接數
    private volatile long limit;
    //是否全部釋放
    private volatile boolean released = false;

    /**
     * Instantiates a LimitLatch object with an initial limit.
     *
     * @param limit - maximum number of concurrent acquisitions of this latch
     */
    public LimitLatch(long limit) {
        this.limit = limit;
        this.count = new AtomicLong(0);
        this.sync = new Sync();
    }

    /**
     * Returns the current count for the latch
     *
     * @return the current count for latch
     */
    //獲取當前計數器
    public long getCount() {
        return count.get();
    }

    /**
     * Obtain the current limit.
     *
     * @return the limit
     */
   //獲取最大連接數
    public long getLimit() {
        return limit;
    }


    /**
     * Sets a new limit. If the limit is decreased there may be a period where
     * more shares of the latch are acquired than the limit. In this case no
     * more shares of the latch will be issued until sufficient shares have been
     * returned to reduce the number of acquired shares of the latch to below
     * the new limit. If the limit is increased, threads currently in the queue
     * may not be issued one of the newly available shares until the next
     * request is made for a latch.
     *
     * @param limit The new limit
     */
   //設置最大連接數
    public void setLimit(long limit) {
        this.limit = limit;
    }


    /**
     * Acquires a shared latch if one is available or waits for one if no shared
     * latch is current available.
     *
     * @throws InterruptedException If the current thread is interrupted
     */
    //增加計數器如果超過最大連接數、則等待并且計數器減一
    public void countUpOrAwait() throws InterruptedException {
        if (log.isDebugEnabled()) {
            log.debug("Counting up[" + Thread.currentThread().getName() + "] latch=" + getCount());
        }
        sync.acquireSharedInterruptibly(1);
    }

    /**
     * Releases a shared latch, making it available for another thread to use.
     *
     * @return the previous counter value
     */
    //減少計數器其實就是減少連接數
    public long countDown() {
        sync.releaseShared(0);
        long result = getCount();
        if (log.isDebugEnabled()) {
            log.debug("Counting down[" + Thread.currentThread().getName() + "] latch=" + result);
        }
        return result;
    }

    /**
     * Releases all waiting threads and causes the {@link #limit} to be ignored
     * until {@link #reset()} is called.
     *
     * @return <code>true</code> if release was done
     */
    //釋放所有線程
    public boolean releaseAll() {
        released = true;
        return sync.releaseShared(0);
    }

    /**
     * Resets the latch and initializes the shared acquisition counter to zero.
     *
     * @see #releaseAll()
     */
    //重置計數器
    public void reset() {
        this.count.set(0);
        released = false;
    }

    /**
     * Returns <code>true</code> if there is at least one thread waiting to
     * acquire the shared lock, otherwise returns <code>false</code>.
     *
     * @return <code>true</code> if threads are waiting
     */
    //是否有等待線程
    public boolean hasQueuedThreads() {
        return sync.hasQueuedThreads();
    }

    /**
     * Provide access to the list of threads waiting to acquire this limited
     * shared latch.
     *
     * @return a collection of threads
     */
    //獲取所有等待線程
    public Collection<Thread> getQueuedThreads() {
        return sync.getQueuedThreads();
    }
}

3.總結Acceptor流程

雖然看上去代碼有點復雜,但是實際上就是一句話概括。獲取socket、并且對socket進行封裝,扔到Poller的隊列中。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,915評論 18 139
  • 說明本次redis集群安裝在rhel6.8 64位機器上,redis版本為3.2.8,redis的gem文件版本為...
    讀或寫閱讀 15,123評論 3 9
  • ¥開啟¥ 【iAPP實現進入界面執行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個線程,因...
    小菜c閱讀 6,511評論 0 17
  • 先來說說我昨天做的夢吧,昨天晚上一直做夢坐電梯,騰云駕霧,飛來飛去,毫無約束。突然嗖的一下,我的眼睛就睜開了。打開...
    懷瑾姑娘閱讀 436評論 0 1
  • 今天離寶寶出生還有27天,三伏天持續高溫,腹中又揣著小火爐,簡直就是太痛苦了,不開空調睡不著,長時間開空調又由于空...
    小七碎碎念閱讀 142評論 0 0