feat[map]: fast concurrent segment lock

This commit is contained in:
godotg
2023-03-25 14:48:03 +08:00
parent ad845b77a3
commit 2b0ce755bd
2 changed files with 224 additions and 1 deletions
@@ -12,6 +12,7 @@
package com.zfoo.protocol.collection;
import com.zfoo.protocol.collection.concurrent.ConcurrentHashMapLongObject;
import com.zfoo.protocol.collection.concurrent.CopyOnWriteHashMapLongObject;
import org.junit.Assert;
import org.junit.Ignore;
@@ -29,7 +30,7 @@ public class ConcurrentTest {
private static final int EXECUTOR_SIZE = Runtime.getRuntime().availableProcessors();
@Test
public void test() throws InterruptedException {
public void copyOnWriteTest() throws InterruptedException {
var map = new CopyOnWriteHashMapLongObject<Integer>();
var num = 1_0000;
var countDownLatch = new CountDownLatch(EXECUTOR_SIZE);
@@ -62,4 +63,39 @@ public class ConcurrentTest {
countDownLatch2.await();
Assert.assertTrue(map.isEmpty());
}
@Test
public void concurrentTest() throws InterruptedException {
var map = new ConcurrentHashMapLongObject<Integer>();
var num = 100_0000;
var countDownLatch = new CountDownLatch(EXECUTOR_SIZE);
for (var i = 0; i < EXECUTOR_SIZE; i++) {
new Thread(new Runnable() {
@Override
public void run() {
for (int j = 0; j < num; j++) {
map.put(j, j);
}
countDownLatch.countDown();
}
}).start();
}
countDownLatch.await();
Assert.assertEquals(map.size(), num);
var countDownLatch2 = new CountDownLatch(EXECUTOR_SIZE);
for (var i = 0; i < EXECUTOR_SIZE; i++) {
new Thread(new Runnable() {
@Override
public void run() {
for (int j = 0; j < num; j++) {
map.remove((long) j);
}
countDownLatch2.countDown();
}
}).start();
}
countDownLatch2.await();
Assert.assertTrue(map.isEmpty());
}
}