ThreadPoolExecutor源码学习(2)-- 在thrift中的应用
thrift作為一個從底到上除去業(yè)務(wù)邏輯代碼,可以生成多種語言客戶端以及服務(wù)器代碼,涵蓋了網(wǎng)絡(luò),IO,進程,線程管理的框架,著實龐大,不過它層次清晰,4層每層解決不同的問題,可以按需取用,相當(dāng)方便。
+-------------------------------------------+ | Server | -- 服務(wù)器進程調(diào)度 | (single-threaded, event-driven etc) | +-------------------------------------------+ | Processor | -- RPC接口處理函數(shù)分發(fā),IDL定義接口的實現(xiàn)將掛接到這里面 | (compiler generated) | +-------------------------------------------+ | Protocol | -- 協(xié)議 | (JSON, compact etc) | +-------------------------------------------+ | Transport | -- 網(wǎng)絡(luò)傳輸 | (raw TCP, HTTP etc) | +-------------------------------------------+其實對于服務(wù)端編程的技術(shù)大牛來說,服務(wù)器調(diào)度可能最能體現(xiàn)個人技術(shù)功底,但是從傳輸層,到序列化這層的工作,確實是比較繁瑣工作,可以直接利用thrift生成的代碼來完成問題。
以上為題外話,在thrift的java代碼實現(xiàn)Server這一層有個TThreadPoolServer,里面對于線程管理就是使用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);//這個就是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ù)的時候,需要調(diào)用shutdown()方法,這個在網(wǎng)上的很多例子都有,但是對于最后一段作者反復(fù)檢查狀態(tài)再退出,這個著實沒有必要的,在shutdown()方法中就有類似的代碼了(jdk1.7);再者java并不會在主線程退出的情況下會對其他線程造成影響,所以這段代碼更顯多余:-D
轉(zhuǎn)載于:https://www.cnblogs.com/elvinni/p/4162982.html
總結(jié)
以上是生活随笔為你收集整理的ThreadPoolExecutor源码学习(2)-- 在thrift中的应用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 机器学习(Machine Learnin
- 下一篇: IDEA中自动导包快捷键