mirror of
https://github.com/tiennm99/zfoo.git
synced 2026-08-23 22:27:28 +00:00
feat[map]: fast concurrent segment lock
This commit is contained in:
@@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user