Search in sources :

Example 1 with KeyedLock

use of org.elasticsearch.common.util.concurrent.KeyedLock in project elasticsearch by elastic.

the class KeyedLockTests method testIfMapEmptyAfterLotsOfAcquireAndReleases.

public void testIfMapEmptyAfterLotsOfAcquireAndReleases() throws InterruptedException {
    ConcurrentHashMap<String, Integer> counter = new ConcurrentHashMap<>();
    ConcurrentHashMap<String, AtomicInteger> safeCounter = new ConcurrentHashMap<>();
    KeyedLock<String> connectionLock = new KeyedLock<String>(randomBoolean());
    String[] names = new String[randomIntBetween(1, 40)];
    for (int i = 0; i < names.length; i++) {
        names[i] = randomRealisticUnicodeOfLengthBetween(10, 20);
    }
    CountDownLatch startLatch = new CountDownLatch(1);
    int numThreads = randomIntBetween(3, 10);
    AcquireAndReleaseThread[] threads = new AcquireAndReleaseThread[numThreads];
    for (int i = 0; i < numThreads; i++) {
        threads[i] = new AcquireAndReleaseThread(startLatch, connectionLock, names, counter, safeCounter);
    }
    for (int i = 0; i < numThreads; i++) {
        threads[i].start();
    }
    startLatch.countDown();
    for (int i = 0; i < numThreads; i++) {
        threads[i].join();
    }
    assertThat(connectionLock.hasLockedKeys(), equalTo(false));
    Set<Entry<String, Integer>> entrySet = counter.entrySet();
    assertThat(counter.size(), equalTo(safeCounter.size()));
    for (Entry<String, Integer> entry : entrySet) {
        AtomicInteger atomicInteger = safeCounter.get(entry.getKey());
        assertThat(atomicInteger, not(Matchers.nullValue()));
        assertThat(atomicInteger.get(), equalTo(entry.getValue()));
    }
}
Also used : CountDownLatch(java.util.concurrent.CountDownLatch) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Entry(java.util.Map.Entry) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) KeyedLock(org.elasticsearch.common.util.concurrent.KeyedLock)

Aggregations

Entry (java.util.Map.Entry)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 KeyedLock (org.elasticsearch.common.util.concurrent.KeyedLock)1