Search code examples
javamultithreadingeventsconcurrencyjava.util.concurrent

Coordinate threads without wait/notify if possible


Besides wait/notify is there a cleaner way of notification of events among threads?
E.g. if I want Thread X to notify ThreadY that something occured is there a better construct in concurrent package than build this on top of wait/notify?
My requirements are simple: ThreadB expects an event to happen. ThreadA is responsible to detect such changes. When a change happens ThreadA informs ThreadB

Update:
I need to do Observer/Observable pattern but I want the observable to block as little as possible when it notifies the observers over the loop.
I.e. the observers would be separate threads and the observable on fire change would "notify" them so as to block as little as possible


Solution

  • You still are vague in your requirements unfortunately. There are three main concurrent primitives you can use for notification at a higherlevel then wait/notify & await/signal.

    You can have a barrier that waits for threads to complete, a barrier that waits for a message from another thread or you can have a barrier that waits a number of threads on an event.

    For the furst you can use a CyclicBarrier, CountdownLatch or Phaser.

    For the second you can use any BlockingQueue whether LinkedBlockingQueue, ArrayBlockingQueue, SynchronousQueue or TransferQueue.

    And for the last you can use an ExecutorService + Future.

    Next question:

    What exactly is an event and what is changing? That is important, if a field is changing you can back your field/event update with a SettableFuture

    Edit:

    Can you include a new library. It appears Akka would work nicely for you.