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.");
}
}
}
|