【发布时间】:2012-04-13 18:08:12
【问题描述】:
我遇到了这个困扰了我好几天的并发问题。
基本上,我希望我的 ThreadPoolExecutor 在关闭之前等待所有任务(任务数未知)完成。
public class AutoShutdownThreadPoolExecutor extends ThreadPoolExecutor{
private static final Logger logger = Logger.getLogger(AutoShutdownThreadPoolExecutor.class);
private int executing = 0;
private ReentrantLock lock = new ReentrantLock();
private final Condition newTaskCondition = lock.newCondition();
private final int WAIT_FOR_NEW_TASK = 120000;
public AutoShutdownThreadPoolExecutor(int coorPoolSize, int maxPoolSize, long keepAliveTime,
TimeUnit seconds, BlockingQueue<Runnable> queue) {
super(coorPoolSize, maxPoolSize, keepAliveTime, seconds, queue);
}
@Override
public void execute(Runnable command) {
lock.lock();
executing++;
lock.unlock();
super.execute(command);
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
try{
lock.lock();
int count = executing--;
if(count == 0) {
newTaskCondition.await(WAIT_FOR_NEW_TASK, TimeUnit.MILLISECONDS);
if(count == 0){
this.shutdown();
logger.info("Shutting down Executor...");
}
}
}
catch (InterruptedException e) {
logger.error("Sleeping task interrupted", e);
}
finally{
lock.unlock();
}
}
}
目的是任务检查任务计数器(正在执行),如果等于0,则阻塞一段时间,稍后释放它的锁,以便其他任务有机会执行而不是关闭执行者太早了。
然而,这并没有发生。 executor中的4个线程全部进入等待状态:
"pool-1-thread-4" prio=6 tid=0x034a1000 nid=0x2d0 waiting on condition [0x039cf000]
"pool-1-thread-3" prio=6 tid=0x034d0400 nid=0x1328 waiting on condition [0x0397f000]
"pool-1-thread-2" prio=6 tid=0x03493400 nid=0x15ec waiting on condition [0x0392f000]
"pool-1-thread-1" prio=6 tid=0x034c3800 nid=0x1fe4 waiting on condition [0x038df000]
如果我在 Runnable 类中添加一个日志语句(应该会降低线程速度),问题似乎就消失了。
public void run() {
// logger.info("Starting task" + taskName);
try {
//doTask();
}
catch (Exception e){
logger.error("task " + taskName + " failed", e);
}
}
问题与这篇文章类似 Java ExecutorService: awaitTermination of all recursively created tasks
我已采用原始海报解决方案并尝试在 afterExecute() 中解决竞争条件,但它不起作用。
请帮助阐明这一点。 谢谢。
【问题讨论】:
-
使用 CountDownLatch 怎么样?
-
任务数事先未知。该程序扫描一个目录以查找其子文件夹中的所有文件,并对每个文件执行一些数字运算任务。
标签: java concurrency