有一个循环轮询从 GenericObjectPool 借用对象。池本身的大小为 1。代码如下 -
final CompletionService completionService = new ExecutorCompletionService(getExecutorServices());
int counter = 0;
for (Iterator iter = AList.iterator(); iter.hasNext();) {
borrowed = this.getPool().borrowObject();
if (borrowed == null) {
throw new Exception("not set");
} else {
completionService.submit(borrowed,borrowed);
counter ++;
}
}
由于池的大小为 1,在第一次借用后,它被耗尽并阻塞。要将对象返回到池中,我想运行一个单独的线程,如下所示 -
new Runnable() {
public void run() {
for (int i = 0; i < counter; i++) {
borrowed = completionService.take().get();
status = borrowed.getStatus();
getPool().returnObject(borrowed);
counter --;
if (status = 1) {
getExecutorServices().shutdownNow();
return;
}
}
}
};
这是对 CompletionService 的阻塞调用,用于在每个线程完成时执行操作并释放它以使其可用于借用。
但是这种设计有一些缺点,比如无法从 Runnable 中读取父级的计数器。