Concurrent Programming in Java , writing code that effectively exploits multiple processors can be very challenging . Effectively exploiting concurrency is becoming more and more important now that Moore's Law is delivering more cores but not faster cores . Have you wondered if a program with as many as five threads in a single processor system can die a catastrophic death in multiple processor systems , showing up 100% CPU usage . Well I found out just that .
A code that was running perfectly fine after a migration to multiple processor system seemed to look choke . Simple reason being IT WAS TIME TO PUT MORE THOUGHTS ON java.util.concurrency package adopted from edu.emory.mathcs.backport.java.util.concurrent . What struck me instantly was CountDownLatch class . My mentor who I believe is the ultimate person and Mr Reliable to fall back during crisis times
Mr. Murali , knew exactly where the problem was !
The typical scenario was that , we had to make sure that all the threads we were using do concurrent jobs and we can't have one racer stop while the system processes someone else's time ,we need all the racers to start at the same time and stop when the leader has finished . The best example I can think of now is that of preparing lemon Rice , though I must agree that I am not a great cook . Lets say we just require 5 main ingredients . The idea is to keep each one of the worker busy . So the ingredients :
1. Rice
2. Lemon
3. Salt
4. Turmeric powder
5 Oil
Imagine that we have run out of all these items at home . We have five servants and we need to prepare the Lemon rice by lunch and we all know that we can start cooking only after all these items arrive . So what we do is we send our five servants to get one item each . Now can we picturize this with our scenario ?
class LemonRicePreparation implements Runnable {
private final CountDownLatch startSignal;
private final CountDownLatch doneSignal;
LemonRicePreparation(CountDownLatch startSignal,
CountDownLatch doneSignal) {
this.startSignal = startSignal;
this.doneSignal = doneSignal;
}
public void run() {
try {
startSignal.await();
doShopping();
doneSignal.countDown();
} catch (InterruptedException ex) {}
}
void doShopping() { ... }
}
- The first is a start signal that prevents any worker from proceeding until the all of them to proceed.
- The second is a completion signal that allows the Cook to wait until all workers have completed buying the items assigned to them .
Trust me what ever code we write cannot be called 100% complete and perfect . There is scope of improvement required everytime .