我在单例中创建了以下执行程序:
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));
}