简体   繁体   English

在单独的线程中将对象返回池

[英]Return Object to Pool in separate Thread

There is a loop which polls for borrowing Objects from a GenericObjectPool. 有一个循环轮询从GenericObjectPool借用对象的循环。 Pool itself is of size 1. Code below - 池本身的大小为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 ++;
                }   
    }   

Since pool is of size 1, after 1st borrow, it is exhausted and blocked. 由于池的大小为1,因此在第一次借用后将其用尽并阻塞。 To return Objects back to pool, I think to run a separate Thread as below - 要将对象返回到池中,我想运行一个单独的线程,如下所示:

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;
            }
        }
    }

};

This is a blocking call to CompletionService for acting on completion of each Thread and releasing it for making it available for borrow. 这是对CompletionService的阻塞调用,用于在每个线程完成时采取行动并将其释放以供借用。

But this design has shortcomings like counter of parent can not be read from Runnable. 但是这种设计有一些缺点,例如无法从Runnable读取父计数器。

The counter is not thread-safe. 计数器不是线程安全的。 Use an AtomicInteger and make it available to both the runnable and the first code block. 使用AtomicInteger并使它可用于可运行代码块和第一个代码块。

我创建了一个CallableDecorator以返回值形式Runnable来监视Thread并对其进行了修复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM