Tuesday, December 15, 2009

java.util.concurrent.CountDownLatch JSR166

java.util.concurrent.CountDownLatch

Assume, in multi-threaded environment, we have an usecase where TWO operations has to be completed before we start the business. How do I monitor these TWO operations result and start the 3rd operation. If any fixed number of operation needs to be done before starting the business then CountDownLatch is the right choice.



We have to create instance of CountDownLatch with an integer, where integer specifies that number of operation has to be done.



CountDownLatch cdl = new CountDownLatch(2);


Where countdownlatch created for 2 activities. Either this 2 activity may be done in a single thread or in multiple threads.

countDown()
Each time this method called from CountDownLatch, subtracts 1 from count. It goes upto ZERO.
await()
This method blocks currentThread until CountDownLatch value comes to ZERO and returns true. if timeout specified in await(long timeout, TimeUnit unit) and If the specified waiting time elapses then the value false is returned.
getCount()
Gives how many operations yet to go. We can eventually use CountDownLatch count to display progressbar also.




import java.util.concurrent.CountDownLatch;

public class CountDownLatchTest {

public static void main(String[] args) {

final CountDownLatch cdl = new CountDownLatch(2);

new Thread() {
@Override
public void run() {
try{sleep(1000);}catch(Exception e){}
System.out.println("T1 complete");
cdl.countDown();
}
}.start();

new Thread() {
@Override
public void run() {
try{sleep(1000);}catch(Exception e){}
System.out.println("T2 complete");
cdl.countDown();
}
}.start();

try {
System.out.println("MainThread waits for T1 and T2 thread to complete");
cdl.await();
} catch (Exception e) {
e.printStackTrace();
}

System.out.println("All threads are completed");
}
}

No comments:

Post a Comment

Recent Posts

Unix Commands | List all My Posts

Texts

This blog intended to share the knowledge and contribute to JAVA Community such a way that by providing samples and pointing right documents/webpages. We try to give our knowledege level best and no guarantee can be claimed on truth. Copyright and Terms of Policy refer blogspot.com