0

Requirement is as follows : Master thread needs to spawn n threads. They will be sending and receiving the message over the channel. Once I receive n/2 + 1 acks then Master will proceed further.

Using CountDownLatch as follows. Problem is that threads whose Acks have not been received (before countdown becomes zero) are lingering around causing out of memory exceptions for new thread creations.

Code is something like this :

final CountDownLatch Acks = new CountDownLatch(n/2+1);

 for (SocketChannel r : n) {
     new Thread() {  // creating n threads over n channels
         @Override
         public void run() {
             synchronized(r) {
                  write the message over channel r
                  received the Ack over channel r
                  Acks.countDown(); <<< used for decrements
             }
         }
 }

 Acks.await();  <<<Master will wait till countDown becomes zero then proceed
recovery
  • 1
  • 1
  • Are you saying that all of the threads Acks *should* be received but are not? Or that you want them to close when the countdown reaches zero regardless of if their ack was received? – Mike Cluck Jun 10 '16 at 18:45
  • Yes I want them to close when the countdown reaches zero regardless of if their ack was received... – recovery Jul 28 '16 at 15:36

3 Answers3

0

Not sure I clearly understand but generally you'll want to use a thread pool to achieve this kind of mechanism.

Joseph M. Dion
  • 356
  • 3
  • 7
0

I would rather use try catch block on this part

received the Ack over channel r

with the exception called "ClosedChannelException", and Master who is awake after Acks reaches 0, should close this connections, the exception will rise, and threads will end.

EDIT: or try to set up timeout on reading: Timeout for SocketChannel doesn't work

Community
  • 1
  • 1
Emil Hotkowski
  • 2,233
  • 1
  • 13
  • 19
0

When you receive n/2 of Aks, you have no control what is going on with the rest of your n/2 threads. One solution could be creating a list of all running threads and as soon as you receive (n/2+1) Aks, you should go over the list and kill remaining threads explicitly. Or you can evaluate approximately the running time of (n/ +1) Aks and set that time as a timeout for all your threads.

v_haruty
  • 86
  • 3