Exemplo n.º 1
0
  /**
   * Runs NUM adder threads, each adder adds 1 (unique) seqno. When all adders are done, we should
   * have NUM elements in the table.
   */
  public void testConcurrentAdd() {
    final int NUM = 100;
    final Table<Integer> buf = new Table<Integer>(3, 10, 0);

    CountDownLatch latch = new CountDownLatch(1);
    Adder[] adders = new Adder[NUM];
    for (int i = 0; i < adders.length; i++) {
      adders[i] = new Adder(latch, i + 1, buf);
      adders[i].start();
    }

    System.out.println("starting threads");
    latch.countDown();
    System.out.print("waiting for threads to be done: ");
    for (Adder adder : adders) {
      try {
        adder.join();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    System.out.println("OK");
    System.out.println("buf = " + buf);
    assert buf.size() == NUM;
  }
Exemplo n.º 2
0
 public void run() {
   try {
     latch.await();
     Util.sleepRandom(10, 500);
     buf.add(seqno, seqno);
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 3
0
  /**
   * Creates a table and fills it to capacity. Then starts a number of adder threads, each trying to
   * add a seqno, blocking until there is more space. Each adder will block until the remover
   * removes elements, so the adder threads get unblocked and can then add their elements to the
   * buffer.
   */
  public void testConcurrentAddAndRemove() throws Exception {
    final int NUM = 5;
    final Table<Integer> buf = new Table<Integer>(3, 10, 0);
    for (int i = 1; i <= 10; i++) buf.add(i, i); // fill the buffer, add() will block now

    CountDownLatch latch = new CountDownLatch(1);
    Adder[] adders = new Adder[NUM];
    for (int i = 0; i < adders.length; i++) {
      adders[i] = new Adder(latch, i + 11, buf);
      adders[i].start();
    }

    System.out.println("releasing threads");
    latch.countDown();
    System.out.print("waiting for threads to be done: ");

    Thread remover =
        new Thread("Remover") {
          public void run() {
            Util.sleep(2000);
            List<Integer> list = buf.removeMany(true, 5);
            System.out.println("\nremover: removed = " + list);
          }
        };
    remover.start();

    for (Adder adder : adders) {
      try {
        adder.join();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }

    remover.join();

    System.out.println("OK");
    System.out.println("buf = " + buf);
    assert buf.size() == 10;
    assertIndices(buf, 5, 5, 15);

    List<Integer> list = buf.removeMany(true, 0);
    System.out.println("removed = " + list);
    assert list.size() == 10;
    for (int i = 6; i <= 15; i++) assert list.contains(i);
    assertIndices(buf, 15, 15, 15);
  }