和朱晔一起复习Java并发(一):线程池 (10)

下面看下相关代码:
首先是队列这块,我们重点关注下重写的offer方法,返回false来增加线程的时机:

@Slf4j public class TomcatTaskQueue extends LinkedBlockingQueue<Runnable> { private transient volatile TomcatThreadPool parent = null; public TomcatTaskQueue(int capacity) { super(capacity); } public void setParent(TomcatThreadPool tp) { parent = tp; } public boolean force(Runnable o) { if (parent == null || parent.isShutdown()) throw new RejectedExecutionException("taskQueue.notRunning"); return super.offer(o); //forces the item onto the queue, to be used if the task is rejected } public boolean force(Runnable o, long timeout, TimeUnit unit) throws InterruptedException { if (parent == null || parent.isShutdown()) throw new RejectedExecutionException("taskQueue.notRunning"); return super.offer(o, timeout, unit); //forces the item onto the queue, to be used if the task is rejected } @Override public boolean offer(Runnable o) { //we can't do any checks if (parent == null) return super.offer(o); //we are maxed out on threads, simply queue the object if (parent.getPoolSize() == parent.getMaximumPoolSize()) { log.info("pool==max, getPoolSize: {}, getMaximumPoolSize:{}, task:{}", parent.getPoolSize(), parent.getMaximumPoolSize(), o); return super.offer(o); } //we have idle threads, just add it to the queue if (parent.getSubmittedCount() <= (parent.getPoolSize())) { log.info("submit<=pool, getPoolSize: {}, getMaximumPoolSize:{}, task:{}", parent.getPoolSize(), parent.getMaximumPoolSize(), o); return super.offer(o); } //if we have less threads than maximum force creation of a new thread if (parent.getPoolSize() < parent.getMaximumPoolSize()) { log.info("Grow thread pool, getPoolSize: {}, getMaximumPoolSize:{}", parent.getPoolSize(), parent.getMaximumPoolSize()); return false; } //if we reached here, we need to add it to the queue log.info("else, getPoolSize: {}, getMaximumPoolSize:{}, task:{}", parent.getPoolSize(), parent.getMaximumPoolSize(), o); return super.offer(o); }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zgdxwx.html