我在单例中创建以下执行程序:
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()支持。
而且线程池没有关闭。
有关信息,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));
}
最佳答案
execute
会抛出RejectedExecutionException
的原因有两个
因为您使用的是
LinkedBlockingQueue
,所以我看到这种情况的唯一方法是因为您关闭了该池。