日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

ThreadPoolExecutor源码学习(2)-- 在thrift中的应用

發(fā)布時(shí)間:2023/12/10 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 ThreadPoolExecutor源码学习(2)-- 在thrift中的应用 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

thrift作為一個(gè)從底到上除去業(yè)務(wù)邏輯代碼,可以生成多種語言客戶端以及服務(wù)器代碼,涵蓋了網(wǎng)絡(luò),IO,進(jìn)程,線程管理的框架,著實(shí)龐大,不過它層次清晰,4層每層解決不同的問題,可以按需取用,相當(dāng)方便。

+-------------------------------------------+ | Server | -- 服務(wù)器進(jìn)程調(diào)度 | (single-threaded, event-driven etc) | +-------------------------------------------+ | Processor | -- RPC接口處理函數(shù)分發(fā),IDL定義接口的實(shí)現(xiàn)將掛接到這里面 | (compiler generated) | +-------------------------------------------+ | Protocol | -- 協(xié)議 | (JSON, compact etc) | +-------------------------------------------+ | Transport | -- 網(wǎng)絡(luò)傳輸 | (raw TCP, HTTP etc) | +-------------------------------------------+

其實(shí)對(duì)于服務(wù)端編程的技術(shù)大牛來說,服務(wù)器調(diào)度可能最能體現(xiàn)個(gè)人技術(shù)功底,但是從傳輸層,到序列化這層的工作,確實(shí)是比較繁瑣工作,可以直接利用thrift生成的代碼來完成問題。

以上為題外話,在thrift的java代碼實(shí)現(xiàn)Server這一層有個(gè)TThreadPoolServer,里面對(duì)于線程管理就是使用ThreadPoolExecutor,下面貼下核心代碼

public void serve() {try {serverTransport_.listen();} catch (TTransportException ttx) {LOGGER.error("Error occurred during listening.", ttx);return;}stopped_ = false;while (!stopped_) {int failureCount = 0;try {TTransport client = serverTransport_.accept();WorkerProcess wp = new WorkerProcess(client);executorService_.execute(wp);//這個(gè)就是ThreadPoolExecutor} catch (TTransportException ttx) {if (!stopped_) {++failureCount;LOGGER.warn("Transport error occurred during acceptance of message.", ttx);}}}executorService_.shutdown();// Loop until awaitTermination finally does return without a interrupted// exception. If we don't do this, then we'll shut down prematurely. We want// to let the executorService clear it's task queue, closing client sockets// appropriately.long timeoutMS = options_.stopTimeoutUnit.toMillis(options_.stopTimeoutVal);long now = System.currentTimeMillis();while (timeoutMS >= 0) {try {executorService_.awaitTermination(timeoutMS, TimeUnit.MILLISECONDS);break;} catch (InterruptedException ix) {long newnow = System.currentTimeMillis();timeoutMS -= (newnow - now);now = newnow;}}}

值得注意的是在執(zhí)行完所有任務(wù)的時(shí)候,需要調(diào)用shutdown()方法,這個(gè)在網(wǎng)上的很多例子都有,但是對(duì)于最后一段作者反復(fù)檢查狀態(tài)再退出,這個(gè)著實(shí)沒有必要的,在shutdown()方法中就有類似的代碼了(jdk1.7);再者java并不會(huì)在主線程退出的情況下會(huì)對(duì)其他線程造成影響,所以這段代碼更顯多余:-D

轉(zhuǎn)載于:https://www.cnblogs.com/elvinni/p/4162982.html

總結(jié)

以上是生活随笔為你收集整理的ThreadPoolExecutor源码学习(2)-- 在thrift中的应用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。