Exemplo n.º 1
0
  @Test
  public void test() throws Exception {
    AsyncMutex mutex = new AsyncMutex();

    final RichFuture<Permit> fPermit1 = mutex.acquire();
    final RichFuture<Permit> fPermit2 = mutex.acquire();
    final RichFuture<Permit> fPermit3 = mutex.acquire();

    assertThat(mutex.getNumPermitsAvailable(), is(0));
    assertThat(mutex.getNumWaiters(), is(2));

    Permit permit1 = fPermit1.apply();

    Future<Permit> waitPermit2 =
        executor.submit(
            new Callable<Permit>() {
              public Permit call() throws Exception {
                return fPermit2.apply();
              }
            });
    Future<Permit> waitPermit3 =
        executor.submit(
            new Callable<Permit>() {
              public Permit call() throws Exception {
                return fPermit3.apply();
              }
            });

    try {
      waitPermit2.get(10, TimeUnit.MILLISECONDS);
      fail("permit 2");
    } catch (TimeoutException e) {
      assertTrue(true);
    }
    try {
      waitPermit3.get(10, TimeUnit.MILLISECONDS);
      fail("permit 3");
    } catch (TimeoutException e) {
      assertTrue(true);
    }

    assertThat(mutex.getNumPermitsAvailable(), is(0));
    assertThat(mutex.getNumWaiters(), is(2));

    permit1.release();

    assertThat(mutex.getNumPermitsAvailable(), is(0));
    assertThat(mutex.getNumWaiters(), is(1));

    Permit permitEither = getEither(waitPermit2, waitPermit3);

    assertThat(mutex.getNumPermitsAvailable(), is(0));
    assertThat(mutex.getNumWaiters(), is(1));

    permitEither.release();

    assertThat(mutex.getNumPermitsAvailable(), is(0));
    assertThat(mutex.getNumWaiters(), is(0));
  }
Exemplo n.º 2
0
 @Override
 public void run() throws Exception {
   Permit permit = getPermit();
   response = permit.init(permitCount);
 }