facebook twitter youtube
by Amit Gupta - no comments

Java 5 provides Lock over synchronized and handed over locking to programmer hands. But it is incomplete without Condition.


condition (since Java 5) is nothing but labeled wait(), notify() & notifyAll(). Let’s understand it with an example;

There are 2 containers: ChocoPowederContainer, WheatPowderContainer. CookieMaker takes some amount of powder from both containers to make a ChocoWheatCookie. There is a Filler who checks container with regular interval. If he finds any container empty, he fills it.


  1. CookieMaker starts N threads say maker1, maker2,.. makerN  to produce cookies.
  2. maker5, maker6, and maker9 found ChocoPowederContainer empty. They took powder from WheatPowderContainer.
  3. maker13, maker10, and maker7 found WheatPowderContainer empty. They took powder from ChocoPowederContainer.
  4. Filler finds ChocoPowederContainer empty. So he filled it and notifyAll() makers. After sometime Filler finds another container empty and fills it and notifyAll() again.

But maker13, maker10, and maker7 want to be notified only when WheatPowderContainer get filled. And maker5, maker6, and maker9 want to be notified only when ChocoPowederContainer get filled.

For the solution, Filler can make 2 Condition objects, say ChocoPowederContainerEmpty and  WheatPowderContainerEmpty. maker5, maker6, and maker9 will call ChocoPowederContainerEmpty.await() and maker13, maker10, and maker7 will call WheatPowderContainer.await().

Filler will call WheatPowderContainerEmpty.signalAll() once WheatPowderContainer is filled. And so on.

I have made a sample program to understand the above example practically. So keep reading…

Amit Gupta

Hey! this is Amit Gupta (amty). By profession, I am a Software Eng. And teaching is my passion. Sometimes I am a teacher, as you can see many technical tutorials on my site, sometimes I am a poet, And sometime just a friend of friends...

Leave a Reply