我在单例中创建了以下执行程序:
final private ExecutorService executor = Executors.newSingleThreadExecutor(new ThreadFactory() {
final ThreadFactory delegate = Executors.defaultThreadFactory();
public Thread newThread(Runnable paramAnonymousRunnable) {
Thread localThread = this.delegate.newThread(paramAnonymousRunnable);
localThread.setName("MyTask-" + localThread.getName());
localThread.setDaemon(XXX.this.daemonThread);
return localThread;
}
});
并且在程序执行过程中,对单例的这个方法的调用很多。这些调用在不同的线程中完成,可能同时进行。
private void send(final String paramString) {
try {
this.executor.execute(new Runnable() {
public void run() {
//DO some interesting stuff
}
});
} catch (Exception localException) {
this.handler.handle(localException);
}
}
在某个时候发生了以下堆栈跟踪:
java.util.concurrent.RejectedExecutionException
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:1774)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:768)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:656)
at java.util.concurrent.Executors$DelegatedExecutorService.execute(Executors.java:589)
at XXXXX.send(XXXX.java:269)
为什么 JVM 会抛出这样的异常?
singleThreadExecutor
由 LinkedBlockingQueue<Runnable>()
支持。
并且线程池没有关闭。
JVM 是 Oracle JDK 1.6。单例是用 Spring 创建的,复制自 java.util.concurrent.Executors
:
public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory));
}
原文由 RJO 发布,翻译遵循 CC BY-SA 4.0 许可协议
execute
会抛出RejectedExecutionException
有两个原因由于您使用的是
LinkedBlockingQueue
,我看到这种情况发生的唯一方法是因为您关闭了池。