Java concurrency: flag / event

I am looking for an non-overloaded flag or event class in java concurrency classes that I can use to verify that something is done and is thread safe. Ideally, something like:

public interface Event { /** returns true if signal() has been called */ public boolean hasOccurred(); /** returns when signal() has been called */ public void await(); public void signal(); } 

Does something like this already exist? I have brain cramps trying to remember

+6
java events concurrency
source share
2 answers

I think you're looking for a CountDownLatch - in particular, create an instance with a number of 1.

Then your operations look like this:

  • hasOccurred : latch.getCount() == 0
  • wait : latch.await()
  • signal : latch.countDown()

If you want something you can reset and use repeatedly, then the CyclicBarrier may be more than what you are looking for. CountDownLatches, after they are launched, cannot be reset.

Edit: It is worth noting that CountDownLatch is more easily compiled for more work than the Event interface you were talking about. So, for example, if you are going to wait for 4 work threads, you can give each employee their own event / 1-count-latch and wait in line for the queue. However, the easiest way is to create a single CountDownLatch with a score of 4 and share it between all the workers (something that does not require any changes in the working logic at all, and this cannot be done simply with a few smaller events).

+14
source share

Do you mean Condition ?

 class BoundedBuffer { final Lock lock = new ReentrantLock(); final Condition notFull = lock.newCondition(); final Condition notEmpty = lock.newCondition(); final Object[] items = new Object[100]; int putptr, takeptr, count; public void put(Object x) throws InterruptedException { lock.lock(); try { while (count == items.length) notFull.await(); items[putptr] = x; if (++putptr == items.length) putptr = 0; ++count; notEmpty.signal(); } finally { lock.unlock(); } } public Object take() throws InterruptedException { lock.lock(); try { while (count == 0) notEmpty.await(); Object x = items[takeptr]; if (++takeptr == items.length) takeptr = 0; --count; notFull.signal(); return x; } finally { lock.unlock(); } } } 
+1
source share

All Articles