正確使用執行緒池的姿勢

2021-09-22 21:33:33 字數 1392 閱讀 2826

# 提示手動建立執行緒池,效果會更好哦。

executorservice fixedthreadpool = executors.newfixedthreadpool(10);

inspection info:

執行緒池不允許使用executors去建立,而是通過threadpoolexecutor的方式,這樣的處理方式讓寫的同學更加明確執行緒池的執行規則,規避資源耗盡的風險。 說明:executors各個方法的弊端:

1)newfixedthreadpool和newsinglethreadexecutor:

主要問題是堆積的請求處理佇列可能會耗費非常大的記憶體,甚至oom。

2)newcachedthreadpool和newscheduledthreadpool:

主要問題是執行緒數最大數是integer.max_value,可能會建立數量非常多的執行緒,甚至oom。

scheduledexecutorservice executorservice = new scheduledthreadpoolexecutor(1,

new basicthreadfactory.builder().namingpattern("example-schedule-pool-%d").daemon(true).build());

threadfactory namedthreadfactory = new threadfactorybuilder()

.setnameformat("demo-pool-%d").build();

//common thread pool

executorservice pool = new threadpoolexecutor(5, 200,

0l, timeunit.milliseconds,

new linkedblockingqueue(1024), namedthreadfactory, new threadpoolexecutor.abortpolicy());

pool.execute(()-> system.out.println(thread.currentthread().getname()));

pool.shutdown();//gracefully shutdown

threadfactory namedthreadfactory = new threadfactorybuilder().setnameformat("thread-call-runner-%d").build();

executorservice fixedthreadpool = new threadpoolexecutor(10,20,200l,timeunit.milliseconds,new linkedblockingqueue(),namedthreadfactory);

執行緒池關閉的姿勢

shutdown方法 平滑的關閉executorservice,當此方法被呼叫時,executorservice停止接收新的任務並且等待已經提交的任務 包含提交正在執行和提交未執行 執行完成。當所有提交任務執行完畢,執行緒池即被關閉。awaittermination方法 接收人timeout和tim...

shape使用正確姿勢

android中常常使用shape來定義控制項的一些顯示屬性,今天看了一些shape的使用,對shape有了大體的了解,稍作總結 先看下面的 solid 實心,就是填充的意思 android color指定填充的顏色 gradient 漸變 android startcolor和android en...

使用快取的正確姿勢

快取是現在系統中必不可少的模組,並且已經成為了高併發高效能架構的乙個關鍵元件。這篇部落格我們來分析一下使用快取的正確姿勢。一般來說,快取有以下三種模式 通俗一點來講就是,同時更新快取和資料庫 cache aside 更新模式 先更新快取,快取負責同步更新資料庫 read write through ...