如何安全关闭GenericKeyedObjectPool? [英] How to shutdown a GenericKeyedObjectPool safely?

查看:151
本文介绍了如何安全关闭GenericKeyedObjectPool?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 GenericKeyedObjectPool 在我的应用程序中. 我可以使用close方法将其关闭,但是我应该如何等待客户端将每个借用的对象返回(并销毁)池中的所有对象?

I have a GenericKeyedObjectPool in my application. I can close it with the close method but how should I wait for the clients to return (and the pool destroys) every borrowed object to the pool?

我需要类似

I need something like ExecutorService.awaitTermination.

推荐答案

为具有所需awaitTermination方法的GenericKeyedObjectPool创建包装.您可以检查closereturnObject调用,并在关闭池并返回每个对象(=当前从该池借入的实例总数为零)的情况下减小闩锁.

Create a wrapper for the GenericKeyedObjectPool which has the required awaitTermination method. You can check the close and the returnObject calls and decrement a latch if the pool is closed and every object was returned (= the total number of instances current borrowed from this pool is zero).

public final class ListenablePool<K, V> {

    private final GenericKeyedObjectPool<K, V> delegate;

    private final CountDownLatch closeLatch = new CountDownLatch(1);

    private final AtomicBoolean closed = new AtomicBoolean();

    public ListenablePool(final KeyedPoolableObjectFactory<K, V> factory) {
        this.delegate = new GenericKeyedObjectPool<K, V>(factory);
    }

    public V borrowObject(final K key) throws Exception {
        return delegate.borrowObject(key);
    }

    public void returnObject(final K key, final V obj) throws Exception {
        try {
            delegate.returnObject(key, obj);
        } finally {
            countDownIfRequired();
        }
    }

    private void countDownIfRequired() {
        if (closed.get() && delegate.getNumActive() == 0) {
            closeLatch.countDown();
        }
    }

    public void close() throws Exception {
        try {
            delegate.close();
        } finally {
            closed.set(true);
            countDownIfRequired();
        }
    }

    public void awaitTermination() throws InterruptedException {
        closeLatch.await();
    }

    public void awaitTermination(final long timeout, final TimeUnit unit) 
            throws InterruptedException {
        closeLatch.await(timeout, unit);
    }

    public int getNumActive() {
        return delegate.getNumActive();
    }

    // other delegate methods
}

这篇关于如何安全关闭GenericKeyedObjectPool?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆