0

I have multiple threads that send the same packet and want all of them to finish before continuing to send the next packet.

I tested out CyclicBarrier with the following code: Test Code (was too long/messy to embed) This worked as expected printing a combination of 0 - 4 then done in a loop

For the packet sender, the code is equivalent except the for loop is:

for(RSocket sendSocket : sendSocketList){
    new Thread(new Send(sendSocket , toServer)).start();
}
barrier.await();

And Send is:

private class Send implements Runnable{
    private RSocket sendSocket;
    private MPacket packet;
    public Send(RSocket sendSocket, MPacket packet){
        this.sendSocket = sendSocket;
        this.packet = packet;
    }
    public void run(){
        sendSocket.send(packet);
        try {
            barrier.await();
        } catch (InterruptedException | BrokenBarrierException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

RSocket.send(packet); functions the same way as a regular socket's writeObject() function, except it blocks until completion (when it receives an ACK). Assuming the networking aspects are correct, am I using CyclicBarrier correctly?

P.S. I should point out if I use a for loop without starting new threads it works as intended i.e.:

for(RSocket sendSocket : sendSocketList){
    sendSocket.send(toServer);
}
user3669539
  • 139
  • 1
  • 9
  • 1
    If the code is too long/messy to post, then reduce it to a COMPLETE compilable, runnable sample that demonstrates the problem. – Jim Garrison Feb 27 '16 at 06:29
  • @JimGarrison sorry, I cannot post the full code since it involves many other classes and is also for a project. The sample I linked is essentially what that particular class is trying to do and is compilable. – user3669539 Feb 27 '16 at 16:43
  • 1
    You haven't actually asked a question or stated a problem. What is the issue you are seeing? _Is_ there a problem? If not, then this is off-topic and belongs on [codereview.se]. – Jim Garrison Feb 27 '16 at 17:20

1 Answers1

0

Yes, the usage of CyclicBarrier is correct in this example.

Just be aware of one point:

  1. According to code the barrier must be initialized to sendSocketList.size()+1 as there is also the main thread invoking await(): barrier = new CyclicBarrier(sendSocketList.size()+1);
Zbynek Vyskovsky - kvr000
  • 18,186
  • 3
  • 35
  • 43