0db9a83767d9bf0680a42d6844235b97201fc6a4
[yangtools.git] / common / util / src / main / java / org / opendaylight / yangtools / util / concurrent / CachedThreadPoolExecutor.java
1 /*
2  * Copyright (c) 2014 Brocade Communications Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.util.concurrent;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.base.MoreObjects;
13 import com.google.common.base.MoreObjects.ToStringHelper;
14 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
15 import java.util.concurrent.BlockingQueue;
16 import java.util.concurrent.LinkedBlockingQueue;
17 import java.util.concurrent.RejectedExecutionException;
18 import java.util.concurrent.RejectedExecutionHandler;
19 import java.util.concurrent.SynchronousQueue;
20 import java.util.concurrent.ThreadPoolExecutor;
21 import java.util.concurrent.TimeUnit;
22 import org.slf4j.LoggerFactory;
23
24 /**
25  * A ThreadPoolExecutor with a specified bounded queue capacity that favors reusing previously
26  * constructed threads, when they are available, over creating new threads.
27  *
28  * <p>See {@link SpecialExecutors#newBoundedCachedThreadPool} for more details.
29  *
30  * @author Thomas Pantelis
31  */
32 public class CachedThreadPoolExecutor extends ThreadPoolExecutor {
33
34     private static final long IDLE_TIMEOUT_IN_SEC = 60L;
35
36     private final ExecutorQueue executorQueue;
37
38     private final String threadPrefix;
39
40     private final int maximumQueueSize;
41
42     private final RejectedTaskHandler rejectedTaskHandler;
43
44     /**
45      * Constructs an instance.
46      *
47      * @param maximumPoolSize
48      *            the maximum number of threads to allow in the pool. Threads will terminate after
49      *            being idle for 60 seconds.
50      * @param maximumQueueSize
51      *            the capacity of the queue.
52      * @param threadPrefix
53      *            the name prefix for threads created by this executor.
54      * @param loggerIdentity
55      *               the class to use as logger name for logging uncaught exceptions from the threads.
56      */
57     @SuppressWarnings("checkstyle:LoggerFactoryClassParameter") // due to loggerIdentity argument usage
58     public CachedThreadPoolExecutor(final int maximumPoolSize, final int maximumQueueSize, final String threadPrefix,
59             Class<?> loggerIdentity) {
60         // We're using a custom SynchronousQueue that has a backing bounded LinkedBlockingQueue.
61         // We don't specify any core threads (first parameter) so, when a task is submitted,
62         // the base class will always try to offer to the queue. If there is an existing waiting
63         // thread, the offer will succeed and the task will be handed to the thread to execute. If
64         // there's no waiting thread, either because there are no threads in the pool or all threads
65         // are busy, the base class will try to create a new thread. If the maximum thread limit has
66         // been reached, the task will be rejected. We specify a RejectedTaskHandler that tries
67         // to offer to the backing queue. If that succeeds, the task will execute as soon as a
68         // thread becomes available. If the offer fails to the backing queue, the task is rejected.
69         super(0, maximumPoolSize, IDLE_TIMEOUT_IN_SEC, TimeUnit.SECONDS,
70                new ExecutorQueue(maximumQueueSize));
71
72         this.threadPrefix = requireNonNull(threadPrefix);
73         this.maximumQueueSize = maximumQueueSize;
74
75         setThreadFactory(ThreadFactoryProvider.builder().namePrefix(threadPrefix)
76                 .logger(LoggerFactory.getLogger(loggerIdentity)).build().get());
77
78         executorQueue = (ExecutorQueue)super.getQueue();
79
80         rejectedTaskHandler = new RejectedTaskHandler(
81                 executorQueue.getBackingQueue(), CountingRejectedExecutionHandler.newAbortPolicy());
82         super.setRejectedExecutionHandler(rejectedTaskHandler);
83     }
84
85     /**
86      * Constructor.
87      * @deprecated Please use {@link #CachedThreadPoolExecutor(int, int, String, Class)} instead.
88      */
89     @Deprecated
90     public CachedThreadPoolExecutor(final int maximumPoolSize, final int maximumQueueSize, final String threadPrefix) {
91         this(maximumPoolSize, maximumQueueSize, threadPrefix, CachedThreadPoolExecutor.class);
92     }
93
94     @Override
95     public void setRejectedExecutionHandler(final RejectedExecutionHandler handler) {
96         rejectedTaskHandler.setDelegateRejectedExecutionHandler(requireNonNull(handler));
97     }
98
99     @Override
100     public RejectedExecutionHandler getRejectedExecutionHandler() {
101         return rejectedTaskHandler.getDelegateRejectedExecutionHandler();
102     }
103
104     @Override
105     public BlockingQueue<Runnable> getQueue() {
106         return executorQueue.getBackingQueue();
107     }
108
109     public long getLargestQueueSize() {
110         return executorQueue.getBackingQueue().getLargestQueueSize();
111     }
112
113     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
114         return toStringHelper;
115     }
116
117     @Override
118     public final String toString() {
119         return addToStringAttributes(MoreObjects.toStringHelper(this)
120                 .add("Thread Prefix", threadPrefix)
121                 .add("Current Thread Pool Size", getPoolSize())
122                 .add("Largest Thread Pool Size", getLargestPoolSize())
123                 .add("Max Thread Pool Size", getMaximumPoolSize())
124                 .add("Current Queue Size", executorQueue.getBackingQueue().size())
125                 .add("Largest Queue Size", getLargestQueueSize())
126                 .add("Max Queue Size", maximumQueueSize)
127                 .add("Active Thread Count", getActiveCount())
128                 .add("Completed Task Count", getCompletedTaskCount())
129                 .add("Total Task Count", getTaskCount())).toString();
130     }
131
132     /**
133      * A customized SynchronousQueue that has a backing bounded LinkedBlockingQueue. This class
134      * overrides the #poll methods to first try to poll the backing queue for a task. If the backing
135      * queue is empty, it calls the base SynchronousQueue#poll method. In this manner, we get the
136      * thread reuse behavior of the SynchronousQueue with the added ability to queue tasks when all
137      * threads are busy.
138      */
139     private static class ExecutorQueue extends SynchronousQueue<Runnable> {
140
141         private static final long serialVersionUID = 1L;
142
143         private static final long POLL_WAIT_TIME_IN_MS = 300;
144
145         @SuppressFBWarnings("SE_BAD_FIELD") // Runnable is not Serializable
146         private final TrackingLinkedBlockingQueue<Runnable> backingQueue;
147
148         ExecutorQueue(final int maxBackingQueueSize) {
149             backingQueue = new TrackingLinkedBlockingQueue<>(maxBackingQueueSize);
150         }
151
152         TrackingLinkedBlockingQueue<Runnable> getBackingQueue() {
153             return backingQueue;
154         }
155
156         @Override
157         public Runnable poll(final long timeout, final TimeUnit unit) throws InterruptedException {
158             long totalWaitTime = unit.toMillis(timeout);
159             long waitTime = Math.min(totalWaitTime, POLL_WAIT_TIME_IN_MS);
160             Runnable task = null;
161
162             // We loop here, each time polling the backingQueue first then our queue, instead of
163             // polling each just once. This is to handle the following timing edge case:
164             //
165             //   We poll the backingQueue and it's empty but, before the call to super.poll,
166             //   a task is offered but no thread is immediately available and the task is put on the
167             //   backingQueue. There is a slight chance that all the other threads could be at the
168             //   same point, in which case they would all call super.poll and wait. If we only
169             //   called poll once, no thread would execute the task (unless/until another task was
170             //   later submitted). But by looping and breaking the specified timeout into small
171             //   periods, one thread will eventually wake up and get the task from the backingQueue
172             //   and execute it, although slightly delayed.
173
174             while (task == null) {
175                 // First try to get a task from the backing queue.
176                 task = backingQueue.poll();
177                 if (task == null) {
178                     // No task in backing - call the base class to wait for one to be offered.
179                     task = super.poll(waitTime, TimeUnit.MILLISECONDS);
180
181                     totalWaitTime -= POLL_WAIT_TIME_IN_MS;
182                     if (totalWaitTime <= 0) {
183                         break;
184                     }
185
186                     waitTime = Math.min(totalWaitTime, POLL_WAIT_TIME_IN_MS);
187                 }
188             }
189
190             return task;
191         }
192
193         @Override
194         public Runnable poll() {
195             Runnable task = backingQueue.poll();
196             return task != null ? task : super.poll();
197         }
198     }
199
200     /**
201      * Internal RejectedExecutionHandler that tries to offer rejected tasks to the backing queue.
202      * If the queue is full, we throw a RejectedExecutionException by default. The client can
203      * override this behavior be specifying their own RejectedExecutionHandler, in which case we
204      * delegate to that handler.
205      */
206     private static class RejectedTaskHandler implements RejectedExecutionHandler {
207
208         private final LinkedBlockingQueue<Runnable> backingQueue;
209         private volatile RejectedExecutionHandler delegateRejectedExecutionHandler;
210
211         RejectedTaskHandler(final LinkedBlockingQueue<Runnable> backingQueue,
212                              final RejectedExecutionHandler delegateRejectedExecutionHandler) {
213             this.backingQueue = backingQueue;
214             this.delegateRejectedExecutionHandler = delegateRejectedExecutionHandler;
215         }
216
217         void setDelegateRejectedExecutionHandler(
218                 final RejectedExecutionHandler delegateRejectedExecutionHandler) {
219             this.delegateRejectedExecutionHandler = delegateRejectedExecutionHandler;
220         }
221
222         RejectedExecutionHandler getDelegateRejectedExecutionHandler() {
223             return delegateRejectedExecutionHandler;
224         }
225
226         @Override
227         public void rejectedExecution(final Runnable task, final ThreadPoolExecutor executor) {
228             if (executor.isShutdown()) {
229                 throw new RejectedExecutionException("Executor has been shutdown.");
230             }
231
232             if (!backingQueue.offer(task)) {
233                 delegateRejectedExecutionHandler.rejectedExecution(task, executor);
234             }
235         }
236     }
237 }