深度解讀Tomcat中的NIO模型

一、I/O復用模型解讀

Tomcat的NIO是基于I/O復用來實現(xiàn)的。對這點一定要清楚,不然我們的討論就不在一個邏輯線上。下面這張圖學習過I/O模型知識的一般都見過,出自《UNIX網(wǎng)絡編程》,I/O模型一共有阻塞式I/O,非阻塞式I/O,I/O復用(select/poll/epoll),信號驅動式I/O和異步I/O。這篇文章講的是I/O復用。

IO復用.png

這里先來說下用戶態(tài)和內核態(tài),直白來講,如果線程執(zhí)行的是用戶代碼,當前線程處在用戶態(tài),如果線程執(zhí)行的是內核里面的代碼,當前線程處在內核態(tài)。更深層來講,操作系統(tǒng)為代碼所處的特權級別分了4個級別。不過現(xiàn)代操作系統(tǒng)只用到了0和3兩個級別。0和3的切換就是用戶態(tài)和內核態(tài)的切換。更詳細的可參照《深入理解計算機操作系統(tǒng)》。I/O復用模型,是同步非阻塞,這里的非阻塞是指I/O讀寫,對應的是recvfrom操作,因為數(shù)據(jù)報文已經(jīng)準備好,無需阻塞。說它是同步,是因為,這個執(zhí)行是在一個線程里面執(zhí)行的。有時候,還會說它又是阻塞的,實際上是指阻塞在select上面,必須等到讀就緒、寫就緒等網(wǎng)絡事件。有時候我們又說I/O復用是多路復用,這里的多路是指N個連接,每一個連接對應一個channel,或者說多路就是多個channel。復用,是指多個連接復用了一個線程或者少量線程(在Tomcat中是Math.min(2,Runtime.getRuntime().availableProcessors()))。

上面提到的網(wǎng)絡事件有連接就緒,接收就緒,讀就緒,寫就緒四個網(wǎng)絡事件。I/O復用主要是通過Selector復用器來實現(xiàn)的,可以結合下面這個圖理解上面的敘述。

Selector圖解.png

二、TOMCAT對IO模型的支持

tomcat支持IO類型圖.png

tomcat從6以后開始支持NIO模型,實現(xiàn)是基于JDK的java.nio包。這里可以看到對read body 和response body是Blocking的。關于這點在第6.3節(jié)源代碼閱讀有重點介紹。

三、TOMCAT中NIO的配置與使用

在Connector節(jié)點配置protocol="org.apache.coyote.http11.Http11NioProtocol",Http11NioProtocol協(xié)議下默認最大連接數(shù)是10000,也可以重新修改maxConnections的值,同時我們可以設置最大線程數(shù)maxThreads,這里設置的最大線程數(shù)就是Excutor的線程池的大小。在BIO模式下實際上是沒有maxConnections,即使配置也不會生效,BIO模式下的maxConnections是保持跟maxThreads大小一致,因為它是一請求一線程模式。

四、NioEndpoint組件關系圖解讀

tomcatnio組成.png

我們要理解tomcat的nio最主要就是對NioEndpoint的理解。它一共包含LimitLatch、Acceptor、Poller、SocketProcessor、Excutor5個部分。LimitLatch是連接控制器,它負責維護連接數(shù)的計算,nio模式下默認是10000,達到這個閾值后,就會拒絕連接請求。Acceptor負責接收連接,默認是1個線程來執(zhí)行,將請求的事件注冊到事件列表。有Poller來負責輪詢,Poller線程數(shù)量是cpu的核數(shù)Math.min(2,Runtime.getRuntime().availableProcessors())。由Poller將就緒的事件生成SocketProcessor同時交給Excutor去執(zhí)行。Excutor線程池的大小就是我們在Connector節(jié)點配置的maxThreads的值。在Excutor的線程中,會完成從socket中讀取http request,解析成HttpServletRequest對象,分派到相應的servlet并完成邏輯,然后將response通過socket發(fā)回client。在從socket中讀數(shù)據(jù)和往socket中寫數(shù)據(jù)的過程,并沒有像典型的非阻塞的NIO的那樣,注冊OP_READ或OP_WRITE事件到主Selector,而是直接通過socket完成讀寫,這時是阻塞完成的,但是在timeout控制上,使用了NIO的Selector機制,但是這個Selector并不是Poller線程維護的主Selector,而是BlockPoller線程中維護的Selector,稱之為輔Selector。詳細源代碼可以參照 第6.3節(jié)。

五、NioEndpoint執(zhí)行序列圖

tomcatnio序列圖.png

在下一小節(jié)NioEndpoint源碼解讀中我們將對步驟1-步驟11依次找到對應的代碼來說明。

六、NioEndpoint源碼解讀

6.1、初始化

無論是BIO還是NIO,開始都會初始化連接限制,不可能無限增大,NIO模式下默認是10000。

public void startInternal() throws Exception {

        if (!running) {
            //省略代碼...
            initializeConnectionLatch();
            //省略代碼...
        }
    }
protected LimitLatch initializeConnectionLatch() {
        if (maxConnections==-1) return null;
        if (connectionLimitLatch==null) {
            connectionLimitLatch = new LimitLatch(getMaxConnections());
        }
        return connectionLimitLatch;
    }
6.2、步驟解讀

下面我們著重敘述跟NIO相關的流程,共分為11個步驟,分別對應上面序列圖中的步驟。
步驟1:綁定IP地址及端口,將ServerSocketChannel設置為阻塞。
這里為什么要設置成阻塞呢,我們一直都在說非阻塞。Tomcat的設計初衷主要是為了操作方便。這樣這里就跟BIO模式下一樣了。只不過在BIO下這里返回的是Socket,NIO下這里返回的是SocketChannel。

public void bind() throws Exception {

        //省略代碼...
        serverSock.socket().bind(addr,getBacklog());
        serverSock.configureBlocking(true); 
        //省略代碼...
        selectorPool.open();
    }

步驟2:啟動接收線程

public void startInternal() throws Exception {

        if (!running) {
            //省略代碼...
            startAcceptorThreads();
        }
    }

//這個方法實際是在它的超類AbstractEndpoint里面    
protected final void startAcceptorThreads() {
        int count = getAcceptorThreadCount();
        acceptors = new Acceptor[count];

        for (int i = 0; i < count; i++) {
            acceptors[i] = createAcceptor();
            Thread t = new Thread(acceptors[i], getName() + "-Acceptor-" + i);
            t.setPriority(getAcceptorThreadPriority());
            t.setDaemon(getDaemon());
            t.start();
        }
    }   

步驟3:ServerSocketChannel.accept()接收新連接

protected class Acceptor extends AbstractEndpoint.Acceptor {

        @Override
        public void run() {
            while (running) {
                
                try {
                    //省略代碼...
                    SocketChannel socket = null;
                    try {                        
                        socket = serverSock.accept();//接收新連接
                    } catch (IOException ioe) {
                        //省略代碼...
                        throw ioe;
                    }
                    //省略代碼...
                    if (running && !paused) {
                        if (!setSocketOptions(socket)) {
                            //省略代碼...
                        }
                    } else {
                        //省略代碼...
                    }
                } catch (SocketTimeoutException sx) {
                    
                } catch (IOException x) {
                    //省略代碼...
                } catch (OutOfMemoryError oom) {
                    //省略代碼...
                } catch (Throwable t) {
                    //省略代碼...
                }
            }
           
        }
    }

步驟4:將接收到的鏈接通道設置為非阻塞
步驟5:構造NioChannel對象
步驟6:register注冊到輪詢線程

protected boolean setSocketOptions(SocketChannel socket) {
        
        try {
            
            socket.configureBlocking(false);//將連接通道設置為非阻塞
            Socket sock = socket.socket();
            socketProperties.setProperties(sock);

            NioChannel channel = nioChannels.poll();//構造NioChannel對象
            //省略代碼...
            getPoller0().register(channel);//register注冊到輪詢線程
        } catch (Throwable t) {
           //省略代碼...
        }
        //省略代碼...
    }

步驟7:構造PollerEvent,并添加到事件隊列

protected ConcurrentLinkedQueue<Runnable> events = new ConcurrentLinkedQueue<Runnable>();
public void register(final NioChannel socket)
        {
            //省略代碼...
            PollerEvent r = eventCache.poll();
            //省略代碼...
            addEvent(r);
        }

步驟8:啟動輪詢線程

public void startInternal() throws Exception {

        if (!running) {
            //省略代碼...
            // Start poller threads
            pollers = new Poller[getPollerThreadCount()];
            for (int i=0; i<pollers.length; i++) {
                pollers[i] = new Poller();
                Thread pollerThread = new Thread(pollers[i], getName() + "-ClientPoller-"+i);
                pollerThread.setPriority(threadPriority);
                pollerThread.setDaemon(true);
                pollerThread.start();
            }
            //省略代碼...
        }
    }

步驟9:取出隊列中新增的PollerEvent并注冊到Selector

public static class PollerEvent implements Runnable {

        //省略代碼...

        @Override
        public void run() {
            if ( interestOps == OP_REGISTER ) {
                try {
                    socket.getIOChannel().register(socket.getPoller().getSelector(), SelectionKey.OP_READ, key);
                } catch (Exception x) {
                    log.error("", x);
                }
            } else {
                //省略代碼...
            }//end if
        }//run
        //省略代碼...
    }

步驟10:Selector.select()

public void run() {
            // Loop until destroy() is called
            while (true) {
                try {
                    //省略代碼...
                    try {
                        if ( !close ) {
                            if (wakeupCounter.getAndSet(-1) > 0) {
                                keyCount = selector.selectNow();
                            } else {
                                keyCount = selector.select(selectorTimeout);
                            }
                            //省略代碼...
                        }
                        //省略代碼...
                    } catch ( NullPointerException x ) {
                        //省略代碼...
                    } catch ( CancelledKeyException x ) {
                        //省略代碼...
                    } catch (Throwable x) {
                        //省略代碼...
                    }
                    //省略代碼...

                    Iterator<SelectionKey> iterator =
                        keyCount > 0 ? selector.selectedKeys().iterator() : null;
                    
                    while (iterator != null && iterator.hasNext()) {
                        SelectionKey sk = iterator.next();
                        KeyAttachment attachment = (KeyAttachment)sk.attachment();
                        
                        if (attachment == null) {
                            iterator.remove();
                        } else {
                            attachment.access();
                            iterator.remove();
                            processKey(sk, attachment);//此方法跟下去就是把SocketProcessor交給Excutor去執(zhí)行
                        }
                    }//while

                    //省略代碼...
                } catch (OutOfMemoryError oom) {
                    //省略代碼...
                }
            }//while
            //省略代碼...
        }

步驟11:根據(jù)選擇的SelectionKey構造SocketProcessor提交到請求處理線程

public boolean processSocket(NioChannel socket, SocketStatus status, boolean dispatch) {
        try {
            //省略代碼...
            SocketProcessor sc = processorCache.poll();
            if ( sc == null ) sc = new SocketProcessor(socket,status);
            else sc.reset(socket,status);
            if ( dispatch && getExecutor()!=null ) getExecutor().execute(sc);
            else sc.run();
        } catch (RejectedExecutionException rx) {
            //省略代碼...
        } catch (Throwable t) {
            //省略代碼...
        }
        //省略代碼...
    }
6.3、NioBlockingSelector和BlockPoller介紹

上面的序列圖有個地方我沒有描述,就是NioSelectorPool這個內部類,是因為在整體理解tomcat的nio上面在序列圖里面不包括它更好理解。在有了上面的基礎后,我們在來說下NioSelectorPool這個類,對更深層了解Tomcat的NIO一定要知道它的作用。NioEndpoint對象中維護了一個NioSelecPool對象,這個NioSelectorPool中又維護了一個BlockPoller線程,這個線程就是基于輔Selector進行NIO的邏輯。以執(zhí)行servlet后,得到response,往socket中寫數(shù)據(jù)為例,最終寫的過程調用NioBlockingSelector的write方法。代碼如下:

public int write(ByteBuffer buf, NioChannel socket, long writeTimeout,MutableInteger lastWrite) throws IOException {  
        SelectionKey key = socket.getIOChannel().keyFor(socket.getPoller().getSelector());  
        if ( key == null ) throw new IOException("Key no longer registered");  
        KeyAttachment att = (KeyAttachment) key.attachment();  
        int written = 0;  
        boolean timedout = false;  
        int keycount = 1; //assume we can write  
        long time = System.currentTimeMillis(); //start the timeout timer  
        try {  
            while ( (!timedout) && buf.hasRemaining()) {  
                if (keycount > 0) { //only write if we were registered for a write  
                    //直接往socket中寫數(shù)據(jù)  
                    int cnt = socket.write(buf); //write the data  
                    lastWrite.set(cnt);  
                    if (cnt == -1)  
                        throw new EOFException();  
                    written += cnt;  
                    //寫數(shù)據(jù)成功,直接進入下一次循環(huán),繼續(xù)寫  
                    if (cnt > 0) {  
                        time = System.currentTimeMillis(); //reset our timeout timer  
                        continue; //we successfully wrote, try again without a selector  
                    }  
                }  
                //如果寫數(shù)據(jù)返回值cnt等于0,通常是網(wǎng)絡不穩(wěn)定造成的寫數(shù)據(jù)失敗  
                try {  
                    //開始一個倒數(shù)計數(shù)器   
                    if ( att.getWriteLatch()==null || att.getWriteLatch().getCount()==0) att.startWriteLatch(1);  
                    //將socket注冊到輔Selector,這里poller就是BlockSelector線程  
                    poller.add(att,SelectionKey.OP_WRITE);  
                    //阻塞,直至超時時間喚醒,或者在還沒有達到超時時間,在BlockSelector中喚醒  
                    att.awaitWriteLatch(writeTimeout,TimeUnit.MILLISECONDS);  
                }catch (InterruptedException ignore) {  
                    Thread.interrupted();  
                }  
                if ( att.getWriteLatch()!=null && att.getWriteLatch().getCount()> 0) {  
                    keycount = 0;  
                }else {  
                    //還沒超時就喚醒,說明網(wǎng)絡狀態(tài)恢復,繼續(xù)下一次循環(huán),完成寫socket  
                    keycount = 1;  
                    att.resetWriteLatch();  
                }  
  
                if (writeTimeout > 0 && (keycount == 0))  
                    timedout = (System.currentTimeMillis() - time) >= writeTimeout;  
            } //while  
            if (timedout)   
                throw new SocketTimeoutException();  
        } finally {  
            poller.remove(att,SelectionKey.OP_WRITE);  
            if (timedout && key != null) {  
                poller.cancelKey(socket, key);  
            }  
        }  
        return written;  
    }

也就是說當socket.write()返回0時,說明網(wǎng)絡狀態(tài)不穩(wěn)定,這時將socket注冊OP_WRITE事件到輔Selector,由BlockPoller線程不斷輪詢這個輔Selector,直到發(fā)現(xiàn)這個socket的寫狀態(tài)恢復了,通過那個倒數(shù)計數(shù)器,通知Worker線程繼續(xù)寫socket動作??匆幌翨lockSelector線程的代碼邏輯:

public void run() {  
            while (run) {  
                try {  
                    ......  
  
                    Iterator iterator = keyCount > 0 ? selector.selectedKeys().iterator() : null;  
                    while (run && iterator != null && iterator.hasNext()) {  
                        SelectionKey sk = (SelectionKey) iterator.next();  
                        KeyAttachment attachment = (KeyAttachment)sk.attachment();  
                        try {  
                            attachment.access();  
                            iterator.remove(); ;  
                            sk.interestOps(sk.interestOps() & (~sk.readyOps()));  
                            if ( sk.isReadable() ) {  
                                countDown(attachment.getReadLatch());  
                            }  
                            //發(fā)現(xiàn)socket可寫狀態(tài)恢復,將倒數(shù)計數(shù)器置位,通知Worker線程繼續(xù)  
                            if (sk.isWritable()) {  
                                countDown(attachment.getWriteLatch());  
                            }  
                        }catch (CancelledKeyException ckx) {  
                            if (sk!=null) sk.cancel();  
                            countDown(attachment.getReadLatch());  
                            countDown(attachment.getWriteLatch());  
                        }  
                    }//while  
                }catch ( Throwable t ) {  
                    log.error("",t);  
                }  
            }  
            events.clear();  
            try {  
                selector.selectNow();//cancel all remaining keys  
            }catch( Exception ignore ) {  
                if (log.isDebugEnabled())log.debug("",ignore);  
            }  
        } 

使用這個輔Selector主要是減少線程間的切換,同時還可減輕主Selector的負擔。

七、關于性能

下面這份報告是我們壓測的一個結果,跟想象的是不是不太一樣?幾乎沒有差別,實際上NIO優(yōu)化的是I/O的讀寫,如果瓶頸不在這里的話,比如傳輸字節(jié)數(shù)很小的情況下,BIO和NIO實際上是沒有差別的。NIO的優(yōu)勢更在于用少量的線程hold住大量的連接。還有一點,我們在壓測的過程中,遇到在NIO模式下剛開始的一小段時間內容,會有錯誤,這是因為一般的壓測工具是基于一種長連接,也就是說比如模擬1000并發(fā),那么同時建立1000個連接,下一時刻再發(fā)送請求就是基于先前的這1000個連接來發(fā)送,還有TOMCAT的NIO處理是有POLLER線程來接管的,它的線程數(shù)一般等于CPU的核數(shù),如果一瞬間有大量并發(fā)過來,POLLER也會頓時處理不過來。

壓測1.jpeg
壓測2.jpeg

八、總結

NIO只是優(yōu)化了網(wǎng)絡IO的讀寫,如果系統(tǒng)的瓶頸不在這里,比如每次讀取的字節(jié)說都是500b,那么BIO和NIO在性能上沒有區(qū)別。NIO模式是最大化壓榨CPU,把時間片都更好利用起來。對于操作系統(tǒng)來說,線程之間上下文切換的開銷很大,而且每個線程都要占用系統(tǒng)的一些資源如內存,有關線程資源可參照這篇文章《一臺java服務器可以跑多少個線程》。因此,使用的線程越少越好。而I/O復用模型正是利用少量的線程來管理大量的連接。在對于維護大量長連接的應用里面更適合用基于I/O復用模型NIO,比如web qq這樣的應用。所以我們要清楚系統(tǒng)的瓶頸是I/O還是CPU的計算。

關注公眾號同步更新技術文章

轉載請注明作者及出處,并附上鏈接http://www.itdecent.cn/p/76ff17bc6dea

參考資料:
http://tomcat.apache.org/tomcat-7.0-doc/config/http.html
http://gearever.iteye.com/blog/1844203
《Tomcat內核設計剖析》
《深入理解計算機操作系統(tǒng)》
《UNIX網(wǎng)絡編程》卷1

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容