Search code examples
javamultithreadingblocking

What blocking object to use?


I need a blocking object for triggering some events. A (single) Consumer should wait for a trigger to occur. Then it does some stuff. Then it again waits for a trigger. The triggers are activated by multiple different threads (Producers). But the Producers do not produce any data. The semantic meaning of such a trigger is: "The Consumer has to do something" (for example recalculate some values, because the underlying data changed). That means even if the trigger is activated multiple times, it should appear to the Consumer as a single trigger.

I thought about using a CountDownLatch or an ArrayBlockingQueue, but they don't seem appropriate.

This is the trigger construct I'd like to use:

public class Trigger{
  private final MagicBlockingObject blockingLatch;

  public void trigger(){
     //activate the blockingLatch, so that a call to waitForTrigger() returns
  } 

  public void waitForTrigger(){
    //read from the blockingLatch. This should block until trigger() is called.
  }
}

Any ideas on what to use for the MagicBlockingObject?

A BlockingQueue seems appropriate, but I did not find a way to restrict it to a single content object without blocking the Producers, if the Queue is already filled.


Solution

  • You could solve this with an ArrayBlockingQueue with a capacity of one:

    public class Trigger{
      private final ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(1);
    
      public void trigger(){
         queue.offer("foo");
      } 
    
      public void waitForTrigger(){
        queue.take();
      }
    }