-
Notifications
You must be signed in to change notification settings - Fork 8
/
DefaultThreadPool.java
279 lines (250 loc) · 11 KB
/
DefaultThreadPool.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.sling.commons.threads.impl;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.sling.commons.threads.ModifiableThreadPoolConfig;
import org.apache.sling.commons.threads.ThreadPool;
import org.apache.sling.commons.threads.ThreadPoolConfig;
import org.apache.sling.commons.threads.ThreadPoolManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The DefaultThreadPool class implements the {@link ThreadPool} interface.
* Instances of this class are managed by the {@link ThreadPoolManager}.
*/
public class DefaultThreadPool
implements ThreadPool {
/** By default we use the logger for this class. */
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
/** The name of this thread pool */
protected final String name;
/** The executor. */
protected ThreadPoolExecutor executor;
protected final ModifiableThreadPoolConfig configuration;
/**
* Create a new thread pool.
* @param name - The name of the thread pool. If null {@link DefaultThreadPoolManager#DEFAULT_THREADPOOL_NAME}
* is used
*/
public DefaultThreadPool(final String name,
final ThreadPoolConfig origConfig) {
// name
if ( name != null ) {
this.name = name;
} else {
this.name = DefaultThreadPoolManager.DEFAULT_THREADPOOL_NAME;
}
this.logger.info("Initializing thread pool [{}] ...", this.name);
this.configuration = new ModifiableThreadPoolConfig(origConfig);
// factory
final ThreadFactory delegateThreadFactory;
if (this.configuration.getFactory() == null) {
logger.debug("Thread pool [{}] ; No ThreadFactory is configured. Will use JVM default thread factory: {}",
this.name, ExtendedThreadFactory.class.getName());
delegateThreadFactory = Executors.defaultThreadFactory();
} else {
delegateThreadFactory = this.configuration.getFactory();
}
// Min pool size
if (this.configuration.getMinPoolSize() < 0) {
this.configuration.setMinPoolSize(1);
this.logger.warn("min-pool-size < 0 for pool \"" + this.name + "\". Set to 1");
}
// Max pool size
if ( this.configuration.getMaxPoolSize() < 0 ) {
this.configuration.setMaxPoolSize(Integer.MAX_VALUE);
}
// Set priority and daemon flag
final ExtendedThreadFactory threadFactory = new ExtendedThreadFactory(
delegateThreadFactory,
this.name,
this.configuration.getPriority(),
this.configuration.isDaemon()
);
// Keep alive time
if (this.configuration.getKeepAliveTime() < 0) {
this.configuration.setKeepAliveTime(1000);
this.logger.warn("keep-alive-time-ms < 0 for pool \"" + this.name + "\". Set to 1000");
}
// Queue
final BlockingQueue<Runnable> queue;
if (this.configuration.getQueueSize() != 0) {
if (this.configuration.getQueueSize() > 0) {
queue = new java.util.concurrent.ArrayBlockingQueue<Runnable>(this.configuration.getQueueSize());
} else {
// SLING-7407 : queue size is -1 (or negative) == unbounded
// in this case the max pool size wouldn't have any effect, since the
// pool is only increased (ie threads only created) when the queue is blocked
// but with an unbounded queue that never happens, thus you'd always get only
// maximum min queue size threads.
// To fix this somewhat odd behaviour, we now automatically set the min to max for this case:
if (this.configuration.getMinPoolSize() < this.configuration.getMaxPoolSize()) {
this.logger.info("min-pool-size (" + configuration.getMinPoolSize() +
") < max-pool-size (" + configuration.getMaxPoolSize() + ") for pool \"" + this.name +
"\" which has unbounded queue (queue size -1). Set to " + configuration.getMaxPoolSize());
this.configuration.setMinPoolSize(configuration.getMaxPoolSize());
}
queue = new LinkedBlockingQueue<Runnable>();
}
} else {
queue = new SynchronousQueue<Runnable>();
}
RejectedExecutionHandler handler = null;
switch (this.configuration.getBlockPolicy()) {
case ABORT :
handler = new ThreadPoolExecutor.AbortPolicy();
break;
case DISCARD :
handler = new ThreadPoolExecutor.DiscardPolicy();
break;
case DISCARDOLDEST :
handler = new ThreadPoolExecutor.DiscardOldestPolicy();
break;
case RUN :
handler = new ThreadPoolExecutor.CallerRunsPolicy();
break;
}
try {
this.executor = new ThreadPoolExecutorCleaningThreadLocals(this.configuration.getMinPoolSize(),
this.configuration.getMaxPoolSize(),
this.configuration.getKeepAliveTime(),
TimeUnit.MILLISECONDS,
queue,
threadFactory,
handler,
new LoggingThreadLocalChangeListener());
} catch (RuntimeException | Error e) {
logger.warn("Unsupported JRE, cannot register ThreadPoolExecutorCleaningThreadLocals due to '{}', fall back to regular ThreadPoolExecutor", e.getMessage(), e);
this.executor = new ThreadPoolExecutor(this.configuration.getMinPoolSize(),
this.configuration.getMaxPoolSize(),
this.configuration.getKeepAliveTime(),
TimeUnit.MILLISECONDS,
queue,
threadFactory,
handler);
}
this.logger.info("Thread pool [{}] initialized.", name);
}
private static class LoggingThreadLocalChangeListener implements ThreadLocalChangeListener {
@Override
public void changed(Mode mode, Thread thread, ThreadLocal<?> threadLocal, Object value) {
LOGGER.debug("Thread '{}' {} ThreadLocal {} with value {}", thread, mode,
threadLocal != null ? threadLocal.getClass() : "<null>", value);
}
@Override
public boolean isEnabled() {
return LOGGER.isDebugEnabled();
}
}
/**
* @see org.apache.sling.commons.threads.ThreadPool#getName()
*/
public String getName() {
return name;
}
/**
* @see org.apache.sling.commons.threads.ThreadPool#getConfiguration()
*/
public ThreadPoolConfig getConfiguration() {
return this.configuration;
}
/**
* @see org.apache.sling.commons.threads.ThreadPool#execute(java.lang.Runnable)
*/
public void execute(final Runnable runnable) {
checkExecutor();
if ( runnable != null ) {
if ( logger.isDebugEnabled() ) {
logOperation("Executing runnable: ", runnable);
}
executor.execute(runnable);
}
}
/**
* @see org.apache.sling.commons.threads.ThreadPool#submit(java.util.concurrent.Callable)
*/
public <T> Future<T> submit(final Callable<T> callable) {
checkExecutor();
if ( logger.isDebugEnabled() ) {
logOperation("Submitting callable: ", callable);
}
return executor.submit(callable);
}
/**
* @see org.apache.sling.commons.threads.ThreadPool#submit(java.lang.Runnable)
*/
public Future<?> submit(final Runnable runnable) {
checkExecutor();
if ( logger.isDebugEnabled() ) {
logOperation("Submitting runnable: ", runnable);
}
return executor.submit(runnable);
}
/**
* Shut down the threadpool.
*/
public void shutdown() {
this.logger.info("Shutting down thread pool [{}] ...", name);
if ( this.executor != null ) {
if (this.configuration.isShutdownGraceful()) {
this.executor.shutdown();
} else {
this.executor.shutdownNow();
}
try {
if (this.configuration.getShutdownWaitTimeMs() > 0) {
if (!this.executor.awaitTermination(this.configuration.getShutdownWaitTimeMs(), TimeUnit.MILLISECONDS)) {
logger.warn("Running commands have not terminated within "
+ this.configuration.getShutdownWaitTimeMs()
+ "ms. Will shut them down by interruption");
this.executor.shutdownNow(); // TODO: shouldn't this be outside the if statement?!
}
}
} catch (final InterruptedException ie) {
this.logger.error("Cannot shutdown thread pool [" + this.name + "]", ie);
}
this.executor = null;
}
this.logger.info("Thread pool [{}] is shut down.", this.name);
}
public ThreadPoolExecutor getExecutor() {
return this.executor;
}
private void checkExecutor() {
if ( this.executor == null ) {
throw new RejectedExecutionException("Thread pool " + this.name + " is already shutdown.");
}
}
private void logOperation(final String msg, final Object obj) {
logger.debug("{} {}, pool={}, active={}, corePoolSize={}, maxPoolSize={}, queueSize={}",
new Object[] {msg, obj, name,
executor.getActiveCount(),
executor.getCorePoolSize(),
executor.getMaximumPoolSize(),
executor.getQueue().size()});
}
}