Search in sources :

Example 16 with RSemaphore

use of org.redisson.api.RSemaphore in project redisson by redisson.

the class RedissonSemaphoreTest method testReducePermits.

@Test
public void testReducePermits() throws InterruptedException {
    RSemaphore s = redisson.getSemaphore("test");
    s.trySetPermits(10);
    s.acquire(10);
    s.reducePermits(5);
    assertThat(s.availablePermits()).isEqualTo(-5);
    s.release(10);
    assertThat(s.availablePermits()).isEqualTo(5);
    s.acquire(5);
    assertThat(s.availablePermits()).isEqualTo(0);
}
Also used : RSemaphore(org.redisson.api.RSemaphore) Test(org.junit.Test)

Example 17 with RSemaphore

use of org.redisson.api.RSemaphore in project redisson by redisson.

the class RedissonSemaphoreTest method testConcurrency_MultiInstance_10_permits.

@Test
public void testConcurrency_MultiInstance_10_permits() throws InterruptedException {
    Assume.assumeFalse(RedissonRuntimeEnvironment.isTravis);
    int iterations = 100;
    final AtomicInteger lockedCounter = new AtomicInteger();
    RSemaphore s = redisson.getSemaphore("test");
    s.trySetPermits(10);
    final AtomicInteger checkPermits = new AtomicInteger(s.availablePermits());
    final CyclicBarrier barrier = new CyclicBarrier(s.availablePermits());
    testMultiInstanceConcurrencySequentiallyLaunched(iterations, r -> {
        RSemaphore s1 = r.getSemaphore("test");
        try {
            s1.acquire();
            barrier.await();
            if (checkPermits.decrementAndGet() > 0) {
                assertThat(s1.availablePermits()).isEqualTo(0);
                assertThat(s1.tryAcquire()).isFalse();
            } else {
                Thread.sleep(50);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
        int value = lockedCounter.get();
        lockedCounter.set(value + 1);
        s1.release();
    });
    System.out.println(lockedCounter.get());
    assertThat(lockedCounter.get()).isLessThan(iterations);
}
Also used : BrokenBarrierException(java.util.concurrent.BrokenBarrierException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) RSemaphore(org.redisson.api.RSemaphore) CyclicBarrier(java.util.concurrent.CyclicBarrier) Test(org.junit.Test)

Aggregations

RSemaphore (org.redisson.api.RSemaphore)17 Test (org.junit.Test)15 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 RLock (org.redisson.api.RLock)2 BrokenBarrierException (java.util.concurrent.BrokenBarrierException)1 CyclicBarrier (java.util.concurrent.CyclicBarrier)1