线程池的取值与拒绝策略

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

猜你喜欢

转载自www.cnblogs.com/silyvin/p/9339137.html