1

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());
    }
}
Vitalii Vitrenko
  • 9,763
  • 4
  • 43
  • 62
stewie
  • 11
  • 1
  • 1
    What do you mean with "this implementation is ok?" ? Do you have any problems with it or does it work as intended? If you have problems, which? – cyberbrain Jan 17 '23 at 16:16
  • OK? It prints the correct answer, so... OK, Right? But the CountDownLatch is redundant with the Futures. `future1.get()` and `future2.get()` _wait_ until the tasks are finished. `countDownLatch.await()` also waits until the tasks are finished. You could completely get rid of the CountDownLatch, and the program still would behave the same way. – Solomon Slow Jan 17 '23 at 16:30

1 Answers1

0

I want to know this implementation is ok?

That totally depends on what you are trying to achieve with this code. As is, your code is simply adding 5 and 4 together and printing the result of 9 to the console. You could simply do that with:

System.out.println(5+4);

If the point of your code is to use a CountDownLatch effectively, then yes you are using it correctly to detect that the Call() method has been invoked on both Person objects in an asynchronous manner before continuing the main method/thread.

Jake Henry
  • 303
  • 1
  • 10