I want to use CountDownLatch
with Callabe
interface. I have Person
class implements Callable
interface which has CountDownLatch
and Integer
, Person#call()
method returns integer value and within finally block countDown()
method called. 2 Threads created by Executors.newFixedThreadPool(2)
and submitted Person
objects within Main class
.I want to know this implementation is ok?
public class Person implements Callable<Integer> {
private final CountDownLatch countDownLatch;
private final Integer count;
public Person(CountDownLatch countDownLatch, Integer count) {
this.countDownLatch = countDownLatch;
this.count = count;
}
@Override
public Integer call() throws Exception {
try {
return count;
} finally {
countDownLatch.countDown();
}
}
}
public class Main {
public static void main(String[] args) throws InterruptedException, ExecutionException {
CountDownLatch countDownLatch = new CountDownLatch(2);
ExecutorService executorService = Executors.newFixedThreadPool(2);
Future<Integer> future1 = executorService.submit(new Person(countDownLatch, 5));
Future<Integer> future2 = executorService.submit(new Person(countDownLatch, 4));
countDownLatch.await();
executorService.shutdown();
System.out.println(future1.get() + future2.get());
}
}