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