BoundedExecutor
Java Concurrency in Practice 一书中的实现有些奇怪。
当 Executor 中有足够多的线程排队或运行时,它应该通过阻塞提交线程来限制向 Executor 提交的任务。
这是实现(在 catch 子句中添加缺少的重新抛出之后):
public class BoundedExecutor {
private final Executor exec;
private final Semaphore semaphore;
public BoundedExecutor(Executor exec, int bound) {
this.exec = exec;
this.semaphore = new Semaphore(bound);
}
public void submitTask(final Runnable command) throws InterruptedException, RejectedExecutionException {
semaphore.acquire();
try {
exec.execute(new Runnable() {
@Override public void run() {
try {
command.run();
} finally {
semaphore.release();
}
}
});
} catch (RejectedExecutionException e) {
semaphore.release();
throw e;
}
}
当我BoundedExecutor
用 anExecutors.newCachedThreadPool()
和 4 来实例化 时,我希望缓存线程池实例化的线程数永远不会超过 4。但实际上,确实如此。我得到了这个小测试程序来创建多达 11 个线程:
public static void main(String[] args) throws Exception {
class CountingThreadFactory implements ThreadFactory {
int count;
@Override public Thread newThread(Runnable r) {
++count;
return new Thread(r);
}
}
List<Integer> counts = new ArrayList<Integer>();
for (int n = 0; n < 100; ++n) {
CountingThreadFactory countingThreadFactory = new CountingThreadFactory();
ExecutorService exec = Executors.newCachedThreadPool(countingThreadFactory);
try {
BoundedExecutor be = new BoundedExecutor(exec, 4);
for (int i = 0; i < 20000; ++i) {
be.submitTask(new Runnable() {
@Override public void run() {}
});
}
} finally {
exec.shutdown();
}
counts.add(countingThreadFactory.count);
}
System.out.println(Collections.max(counts));
}
我认为在信号量的释放和任务结束之间有一个很小的时间框架,另一个线程可以在释放线程尚未完成时获得许可并提交任务。换句话说,它有一个竞争条件。
有人可以证实这一点吗?