Coordinating Runnable tasks using CountDownLatch


/ Published in: Java
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  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. }

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.