18

我有多个消费者线程正在等待CountDownLatch大小为 1 的await(). 我有一个生产者线程,countDown()它在成功完成时调用。

当没有错误时,这很有效。

但是,如果生产者检测到错误,我希望它能够向消费者线程发出错误信号。理想情况下,我可以让生产者调用类似的东西,abortCountDown()并让所有消费者收到 InterruptedException 或其他一些异常。我不想调用countDown(),因为这需要我的所有消费者线程在调用await(). 我宁愿他们只收到一个他们已经知道如何处理的异常。

我知道中止设施在CountDownLatch. 是否有另一个同步原语可以轻松适应以有效创建CountDownLatch支持中止倒计时的同步原语?

4

5 回答 5

17

JB Nizet 给出了一个很好的答案。我拿了他的,稍微打磨了一下。结果是一个名为 AbortableCountDownLatch 的 CountDownLatch 的子类,它向该类添加了一个“abort()”方法,该方法将导致所有等待锁存器的线程接收 AbortException(InterruptedException 的子类)。

此外,与 JB 的类不同,AbortableCountDownLatch 将在中止时立即中止所有阻塞线程,而不是等待倒计时达到零(对于使用计数>1 的情况)。

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class AbortableCountDownLatch extends CountDownLatch {
    protected boolean aborted = false;

    public AbortableCountDownLatch(int count) {
        super(count);
    }


   /**
     * Unblocks all threads waiting on this latch and cause them to receive an
     * AbortedException.  If the latch has already counted all the way down,
     * this method does nothing.
     */
    public void abort() {
        if( getCount()==0 )
            return;

        this.aborted = true;
        while(getCount()>0)
            countDown();
    }


    @Override
    public boolean await(long timeout, TimeUnit unit) throws InterruptedException {
        final boolean rtrn = super.await(timeout,unit);
        if (aborted)
            throw new AbortedException();
        return rtrn;
    }

    @Override
    public void await() throws InterruptedException {
        super.await();
        if (aborted)
            throw new AbortedException();
    }


    public static class AbortedException extends InterruptedException {
        public AbortedException() {
        }

        public AbortedException(String detailMessage) {
            super(detailMessage);
        }
    }
}
于 2012-05-04T20:37:01.913 回答
13

在内部使用 CountDownLatch 将此行为封装在特定的更高级别的类中:

public class MyLatch {
    private CountDownLatch latch;
    private boolean aborted;
    ...

    // called by consumers
    public void await() throws AbortedException {
        latch.await();
        if (aborted) {
            throw new AbortedException();
        }
    }

    // called by producer
    public void abort() {
        this.aborted = true;
        latch.countDown();
    }

    // called by producer
    public void succeed() {
        latch.countDown();
    }
}
于 2012-05-04T18:08:33.507 回答
4

您可以创建一个包装器CountDownLatch,以提供取消服务员的能力。它将需要跟踪等待的线程并在它们超时时释放它们,并记住闩锁已被取消,因此未来的调用await将立即中断。

public class CancellableCountDownLatch
{
    final CountDownLatch latch;
    final List<Thread> waiters;
    boolean cancelled = false;

    public CancellableCountDownLatch(int count) {
        latch = new CountDownLatch(count);
        waiters = new ArrayList<Thread>();
    }

    public void await() throws InterruptedException {
        try {
            addWaiter();
            latch.await();
        }
        finally {
            removeWaiter();
        }
    }

    public boolean await(long timeout, TimeUnit unit) throws InterruptedException {
        try {
            addWaiter();
            return latch.await(timeout, unit);
        }
        finally {
            removeWaiter();
        }
    }

    private synchronized void addWaiter() throws InterruptedException {
        if (cancelled) {
            Thread.currentThread().interrupt();
            throw new InterruptedException("Latch has already been cancelled");
        }
        waiters.add(Thread.currentThread());
    }

    private synchronized void removeWaiter() {
        waiters.remove(Thread.currentThread());
    }

    public void countDown() {
        latch.countDown();
    }

    public synchronized void cancel() {
        if (!cancelled) {
            cancelled = true;
            for (Thread waiter : waiters) {
                waiter.interrupt();
            }
            waiters.clear();
        }
    }

    public long getCount() {
        return latch.getCount();
    }

    @Override
    public String toString() {
        return latch.toString();
    }
}
于 2012-05-04T18:10:52.383 回答
0

CountDownLatch您可以使用ReentrantLock允许访问其受保护方法的 a推出自己的getWaitingThreads方法。

例子:

public class FailableCountDownLatch {
    private static class ConditionReentrantLock extends ReentrantLock {
        private static final long serialVersionUID = 2974195457854549498L;

        @Override
        public Collection<Thread> getWaitingThreads(Condition c) {
            return super.getWaitingThreads(c);
        }
    }

    private final ConditionReentrantLock lock = new ConditionReentrantLock();
    private final Condition countIsZero = lock.newCondition();
    private long count;

    public FailableCountDownLatch(long count) {
        this.count = count;
    }

    public void await() throws InterruptedException {
        lock.lock();
        try {
            if (getCount() > 0) {
                countIsZero.await();
            }
        } finally {
            lock.unlock();
        }
    }

    public boolean await(long time, TimeUnit unit) throws InterruptedException {
        lock.lock();
        try {
            if (getCount() > 0) {
                return countIsZero.await(time, unit);
            }
        } finally {
            lock.unlock();
        }
        return true;
    }

    public long getCount() {
        lock.lock();
        try {
            return count;
        } finally {
            lock.unlock();
        }
    }

    public void countDown() {
        lock.lock();
        try {
            if (count > 0) {
                count--;

                if (count == 0) {
                    countIsZero.signalAll();
                }
            }
        } finally {
            lock.unlock();
        }
    }

    public void abortCountDown() {
        lock.lock();
        try {
            for (Thread t : lock.getWaitingThreads(countIsZero)) {
                t.interrupt();
            }
        } finally {
            lock.unlock();
        }
    }
}

您可能希望更改此类以在取消后引发InterruptedException新的调用。如果您需要该功能,await您甚至可以扩展此类。CountDownLatch

于 2012-05-04T18:19:39.200 回答
0

从 Java 8 开始,您可以为此使用 CompletableFuture。一个或多个线程可以调用阻塞的 get() 方法:

CompletableFuture<Void> cf = new CompletableFuture<>();
try {
  cf.get();
} catch (ExecutionException e) {
  //act on error
}

另一个线程可以成功地完成它,也可以cf.complete(null)异常地完成它cf.completeExceptionally(new MyException())

于 2021-03-22T10:26:25.720 回答