如何提高ConcurrentHashMap使用效率

65 阅读1分钟

适用场景: 高并发场景下,暂存一批数据,然后过一段时间使用(不关心数据的顺序性)

解决方案: 通过两个map,配合atomic原子类,解决并发场景下(ConcurrentHashMap加锁),读写不相互阻塞;

public class ConcurrentHashMapTest {
    private final ConcurrentHashMap<String, String> map1 = new ConcurrentHashMap<>();

    private final ConcurrentHashMap<String, String> map2 = new ConcurrentHashMap<>();

    private final AtomicLong atomicCount = new AtomicLong(0);


    public List<String> getValues() {
        //自增
        atomicCount.addAndGet(1);
        List<String> result;
        if (atomicCount.get() % 2 == 0) {
            result = CollectionUtil.list(false, map1.values());
            map1.clear();;
        } else {
            result = CollectionUtil.list(false, map2.values());
            map2.clear();
        }
        return result;
    }

    public Boolean setValue(String key, String value) {
        if (atomicCount.get() % 2 == 0) {
            map2.putIfAbsent(key, value);
        } else {
            map1.putIfAbsent(key, value);
        }
        return true;
    }
}

参考:京东hotkey框架代码,致敬