線程池的取值與拒絕策略
阿新 • • 發佈:2018-07-20
() com pub 分析 call class implement 導致 error
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
先估算一個並發數,即為corePoolSize,*1.2為maximumPoolSize
workQueue長度=可容忍的時間/線程平均響應時間*corePoolSize,假設每個線程0.1s,可以容忍2s內給客戶端返回,則隊列可容納20倍的corePoolSize,
比如有線程池有10個線程,0.1秒過10個線程,2s過20*10=200,容量可取200,最多2s隊列末尾的線程也可以獲得執行並返回給客戶端
參考:https://www.cnblogs.com/waytobestcoder/p/5323130.html
==================================================================
jvm內存有限,不可能容納無限線程,否則內存爆掉,我們需要一定的拒絕策略,首先要拒絕,其次又要保留一定的信息,以便日後分析作出調整
private static class MyRejectedExecutionHandler implements RejectedExecutionHandler {
private static Logger LOGGER = LoggerFactory.getLogger(MyRejectedExecutionHandler.class);
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
LOGGER.error("thread discard");
}
}
註意,如果是callable get方式,這種情況會導致get無限阻塞,註意設置超時限制
==================================================================
https://www.cnblogs.com/longzhaoyu/p/4539341.html這篇文章比較有意思,厘米的拒絕策略:
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { if (!executor.isShutdown()) { executor.execute(r); } }
stack over flow
線程池的取值與拒絕策略