Search in sources :

Example 1 with LocalLock

use of com.alipay.sofa.jraft.rhea.storage.LocalLock in project sofa-jraft by sofastack.

the class MemoryKVStoreTest method tryLockWith.

/**
 * Test method: {@link MemoryRawKVStore#tryLockWith(byte[], byte[], boolean, DistributedLock.Acquirer, KVStoreClosure)}
 */
@Test
public void tryLockWith() throws InterruptedException {
    byte[] lockKey = makeKey("lock_test");
    final DistributedLock<byte[]> lock = new LocalLock(lockKey, 3, TimeUnit.SECONDS, this.kvStore);
    assertNotNull(lock);
    assertTrue(lock.tryLock());
    assertTrue(lock.tryLock());
    assertTrue(lock.tryLock(3001, TimeUnit.MILLISECONDS));
    final CountDownLatch latch = new CountDownLatch(1);
    new Thread(() -> {
        final DistributedLock<byte[]> lock2 = new LocalLock(lockKey, 3, TimeUnit.SECONDS, this.kvStore);
        try {
            assertTrue(!lock2.tryLock());
        } finally {
            latch.countDown();
        }
    }, "lock1-thread").start();
    latch.await();
    lock.unlock();
    assertTrue(lock.tryLock());
    lock.unlock();
}
Also used : DistributedLock(com.alipay.sofa.jraft.rhea.util.concurrent.DistributedLock) CountDownLatch(java.util.concurrent.CountDownLatch) LocalLock(com.alipay.sofa.jraft.rhea.storage.LocalLock) Test(org.junit.Test)

Example 2 with LocalLock

use of com.alipay.sofa.jraft.rhea.storage.LocalLock in project sofa-jraft by sofastack.

the class RocksKVStoreTest method tryLockWith.

/**
 * Test method: {@link RocksRawKVStore#tryLockWith(byte[], byte[], boolean, DistributedLock.Acquirer, KVStoreClosure)}
 */
@Test
public void tryLockWith() throws InterruptedException {
    byte[] lockKey = makeKey("lock_test");
    final DistributedLock<byte[]> lock = new LocalLock(lockKey, 3, TimeUnit.SECONDS, this.kvStore);
    assertNotNull(lock);
    assertTrue(lock.tryLock());
    assertTrue(lock.tryLock());
    assertTrue(lock.tryLock(3001, TimeUnit.MILLISECONDS));
    final CountDownLatch latch = new CountDownLatch(1);
    new Thread(() -> {
        final DistributedLock<byte[]> lock2 = new LocalLock(lockKey, 3, TimeUnit.SECONDS, this.kvStore);
        try {
            assertFalse(lock2.tryLock());
        } finally {
            latch.countDown();
        }
    }, "lock1-thread").start();
    latch.await();
    lock.unlock();
    assertTrue(lock.tryLock());
    lock.unlock();
}
Also used : DistributedLock(com.alipay.sofa.jraft.rhea.util.concurrent.DistributedLock) CountDownLatch(java.util.concurrent.CountDownLatch) LocalLock(com.alipay.sofa.jraft.rhea.storage.LocalLock) Test(org.junit.Test)

Aggregations

LocalLock (com.alipay.sofa.jraft.rhea.storage.LocalLock)2 DistributedLock (com.alipay.sofa.jraft.rhea.util.concurrent.DistributedLock)2 CountDownLatch (java.util.concurrent.CountDownLatch)2 Test (org.junit.Test)2