Posted By

liqweed on 09/30/08


Tagged

concurrency


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

niko_s


Coordinating Runnable tasks using CountDownLatch


 / Published in: Java
 

URL: http://java.sun.com/j2se/1.6.0/docs/api/java/util/concurrent/CountDownLatch.html

A simple way to parallelize a for loop in Java. Wrapping each iteration (task) with a Runnable, executing them with an ExecutorService (to pool threads) and coordinating them with a simple CountDownLatch.

Due to Java's lack of closures, this simple scenario is rather verbose.

  1. ExecutorService executorService = Executors.newFixedThreadPool(5);
  2. int tasksCount = 10;
  3. final CountDownLatch latch = new CountDownLatch(tasksCount);
  4. for (int i = 0; i < tasksCount; i++ ) {
  5. executorService.execute(new Runnable() {
  6. public void run() {
  7. try {
  8. // Do some work;
  9. } finally {
  10. latch.countDown();
  11. }
  12. }
  13. });
  14. }
  15. try {
  16. latch.await();
  17. } catch (InterruptedException e) {
  18. // todo >> handle exception
  19. }
  20. // All done!
  21. // Do some more work
  22. }

Report this snippet  

You need to login to post a comment.