/**
  * Send num unicasts on both channels and verify the other end received them
  *
  * @param num
  * @throws Exception
  */
 private void sendToEachOtherAndCheck(int num) throws Exception {
   for (int i = 1; i <= num; i++) {
     a.send(b_addr, "m" + i);
     b.send(a_addr, "m" + i);
   }
   List<Message> l1 = r1.getMessages();
   List<Message> l2 = r2.getMessages();
   for (int i = 0; i < 10; i++) {
     if (l1.size() == num && l2.size() == num) break;
     Util.sleep(500);
   }
   System.out.println("l1 = " + print(l1));
   System.out.println("l2 = " + print(l2));
   assert l1.size() == num;
   assert l2.size() == num;
 }
 private static void sendAndCheck(JChannel channel, Address dest, int num, MyReceiver receiver)
     throws Exception {
   receiver.clear();
   for (int i = 1; i <= num; i++) channel.send(dest, "m" + i);
   List<Message> list = receiver.getMessages();
   for (int i = 0; i < 20; i++) {
     if (list.size() == num) break;
     Util.sleep(500);
   }
   System.out.println("list = " + print(list));
   int size = list.size();
   assert size == num : "list has " + size + " elements: " + list;
 }
  /**
   * Tests concurrent reception of multiple messages with a different conn_id
   * (https://issues.jboss.org/browse/JGRP-1347)
   */
  public void testMultipleConcurrentResets() throws Exception {
    sendAndCheck(a, b_addr, 1, r2);

    // now close connection on A unilaterally
    System.out.println("==== Closing the connection on A");
    removeConnection(u1, b_addr);

    r2.clear();

    final UNICAST unicast = (UNICAST) b.getProtocolStack().findProtocol(UNICAST.class);

    int NUM = 10;

    final List<Message> msgs = new ArrayList<Message>(NUM);

    for (int i = 1; i <= NUM; i++) {
      Message msg = new Message(b_addr, a_addr, "m" + i);
      UNICAST.UnicastHeader hdr = UNICAST.UnicastHeader.createDataHeader(1, (short) 2, true);
      msg.putHeader(unicast.getId(), hdr);
      msgs.add(msg);
    }

    Thread[] threads = new Thread[NUM];
    final CyclicBarrier barrier = new CyclicBarrier(NUM + 1);
    for (int i = 0; i < NUM; i++) {
      final int index = i;
      threads[i] =
          new Thread() {
            public void run() {
              try {
                barrier.await();
                unicast.up(new Event(Event.MSG, msgs.get(index)));
              } catch (Exception e) {
                e.printStackTrace();
              }
            }
          };
      threads[i].start();
    }

    barrier.await();
    for (Thread thread : threads) thread.join();

    List<Message> list = r2.getMessages();
    System.out.println("list = " + print(list));

    assert list.size() == 1
        : "list must have 1 element but has " + list.size() + ": " + print(list);
  }