We Recommend

Java How to Program Java How to Program
Takes a new tools-based approach to Web application development that uses Netbeans 5.5 and Java Studio Creator 2 to create and consume Web Services. Features new AJAX-enabled, Web applications built with JavaServer Faces (JSF), Java Studio Creator 2 and the Java Blueprints AJAX Components. Includes new topics throughout, such as JDBC 4, SwingWorker for multithreaded GUIs, GroupLayout, Java Desktop Integration Components (JDIC), and much more.


Posted By

liqweed on 09/30/08


Tagged

concurrency


Versions (?)


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.