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.
- CookieMaker starts N threads say maker1, maker2,.. makerN to produce cookies.
- maker5, maker6, and maker9 found ChocoPowederContainer empty. They took powder from WheatPowderContainer.
- maker13, maker10, and maker7 found WheatPowderContainer empty. They took powder from ChocoPowederContainer.
- 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…