Question : ConcurrentLatch in Java.

Is this a correct implementation of Concurrent Latch?

In the below scenario, I want the isEligibleForClearDown() to be run simultaneously. Please suggest.

          while(iterator != null && iterator.hasNext()) {
                final CountDownLatch startLatch = new CountDownLatch(threads);
                for(int i = 0; i < 10; i++) {
                      ExecutorService executorService = Executors.newFixedThreadPool(threads); // start 10 threads.
                      if(iterator.hasNext()) {
                            final OrderModel model = (OrderModel) iterator.next();
                            executorService.execute(new Runnable() {
                                  public void run() {
                                        Calendar now = Calendar.getInstance(TimeZone.getTimeZone("Europe/London"));
                                      if (isEligibleForClearDown(model, master.getCleardownFields().getClearDownReqFrom(), now)){
                                            if (model.getOrderFields().hasParentOrderId()){
                                                  //add all Child orders to final result
                                                  results.add(model);
                                            } else {
                                                  //add parent orders to the parent list
                                                  parentOrders.add(model);
                                            }
                                      }
                                      startLatch.countDown();
                                  }                         
                            });
                      } else {
                            if(startLatch.getCount() > 0) { // decrement counter until latch is zero.
                                  try {
                                          startLatch.await();
                                    } catch (InterruptedException e) {
                                          LOGGER.error("Interrupted Exception while waiting for the countdown latch to end.");
                                    }
                            }
                      }
                }
              try {
                        startLatch.await(); // wait until the first 10 threads complete processing.
                  } catch (InterruptedException e) {
                        LOGGER.error("Interrupted Exception while waiting for the countdown latch to end.");
                  }
          }

Answer : ConcurrentLatch in Java.

First thing I'd recommend is moving your executor service outside of the loop.  You really only need to create that once.  Depending on your implementation, you may be able to make it a class variable, either a static that is shared by all instances of this class or a private member if each class needs its own thread pool.  Either way, as long as you don't shut the service down, you'll be able to reuse those threads instead of incurring the overhead of starting them every time.  If multiple calls to this method will need to run simultaneously, move the executor service creation back into the method, but outside of the loop.

It also looks like you're creating 10 thread pools, with 10 threads each to process each order.  The code I've attached is reworked to process all provided orders with 10 threads.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
public class ClearDownService {
    private int threads;
    private ExecutorService executorService;

    public ClearDownService(int threads) {
        if (threads < 1) {
            throw new IllegalArgumentException("Threads must be >= 1.");
        }
        this.threads = threads;
        this.executorService = Executors.newFixedThreadPool(this.threads);
    }

    // I modified your iteration code to assume you have some Collection of OrderModel objects
    // that you are using to get the iterator.  Since you are using JDK 1.5+, its much more
    // readable and maintainable to use Generics instead of casting the return of iterator.next().
    // I also modified your iteration code to use the built-in foreach construct.
    public void checkOrders(Collection<OrderModel> orders) {
        // Initialize latch for the total number of orders, instead of threads.
        // This ensures all orders are processed before this method completes
        final CountDownLatch startLatch = new CountDownLatch(orders.size());

        // since you are using JDK 1.5+, easier to read and maintain if you use generics
        // and the built-in foreach instead of the iterator
        for (final OrderModel model : orders) {
            executorService.submit(new Runnable() {
                public void run() {
                    try {
                        Calendar now = Calendar.getInstance(TimeZone.getTimeZone("Europe/London"));
                        if (isEligibleForClearDown(model, master.getCleardownFields().getClearDownReqFrom(), now)) {
                            if (model.getOrderFields().hasParentOrderId()) {
                                // add all Child orders to final result
                                results.add(model);
                            } else {
                                // add parent orders to the parent list
                                parentOrders.add(model);
                            }
                        }
                    } finally {
                        // putting this in a finally block ensures it gets called regardless
                        // of any exceptions that occur in the body of the method
                        startLatch.countDown();
                    }
                }
            });
        }
        try {
            startLatch.await(); // wait for all objects to complete processing
        } catch (InterruptedException e) {
            LOGGER.error("Interrupted Exception while waiting for the countdown latch to end.");
        }
    }
}
Random Solutions  
 
programming4us programming4us