0

I have two threads with countDownLatch set to 1, so that, when the first threads finishes the second should starts. And what I want to do is, when the second finishes its task, I want to get the data computed from both threads to do some operations.

now my question is, is there any way to know if the CountDownLatch object finished its task?

Update

is it safe to use

while (latch.getcountDown()==0) {
 // do the calculations on the data processed by the two threads
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
Amrmsmb
  • 1
  • 27
  • 104
  • 226
  • use thread.notify; you can also use http://www.tutorialspoint.com/java/lang/object_notifyall.htm link for refereence – Saurabh Jhunjhunwala May 03 '15 at 10:23
  • @SaurabhJhunjhunwala do u mean latch.notify?? would you provide eample for both – Amrmsmb May 03 '15 at 10:26
  • a) It is unclear what you mean by "finished its task"? CountDownLatch doesn't _do_ any tasks. b) Is there any reason not to use Executors and Futures? Looks like the perfect tool for a thing like this. – Sergei Tachenov May 03 '15 at 10:31
  • @SergeyTachenov what i mean is, as the latch is set initially to 1, first thread will start and the i call latch.countdown()..then thread2 will starts when thread 1 calls .countdown() and the latch reaches 0. – Amrmsmb May 03 '15 at 10:41
  • Still makes no sense to me (as does your update because the loop will run forever once the latch is open). CountDownLatch is designed to use that someone calls `countDown()` N times, and at the same time someone else calls `await()` and waits for the latch to open. Perhaps you should explain in your answer exactly what you need and provide an example? – Sergei Tachenov May 03 '15 at 10:49
  • @SergeyTachenov i am know learning the Executors and Futures. but is there any way to know if the executor finished, so that when it is finished i can start working on the results returned from the callable? – Amrmsmb May 03 '15 at 11:33
  • 1
    That's exactly what the `Future.get()` and `Future.isDone()` methods for. – Sergei Tachenov May 03 '15 at 11:38
  • @SergeyTachenov please i have just a question, in case i am using executorService to submit runnable , is there any way to indicate if the executor finished? – Amrmsmb May 03 '15 at 12:35

2 Answers2

0

Yes when your thread finishes and is capable of say accepting request or a particular task, it call countDown method on latch. And on the other hand in your main thread (or your co-ordinator thread), block on await method on latch.

Now whenever 'x' slave threads completes their task and calls countDown, master knows about the same and comes out of await and does further processing.

SMA
  • 36,381
  • 8
  • 49
  • 73
0

Have you tried 'join' for the threads. Instead of using a heavy latch join might do the trick.

acearch
  • 343
  • 1
  • 8