Spring—ConcurrentReferenceHashMap

ConcurrentReferenceHashMap与ConcurrentHashMap的区别是ConcurrentReferenceHashMap能指定所存放对象的引用级别,适用于并发下Map的数据缓存。

注:Java四种对象引用级别:强引用、软引用、弱引用、虚引用

测试代码:

注:用弱引用来及时查看效果。

public class TestConcurrentReferenceHashMap {

    public static void main(String[] args) {
        ConcurrentReferenceHashMap map = new ConcurrentReferenceHashMap(16, ConcurrentReferenceHashMap.ReferenceType.WEAK);
        map.put("key","val");

        System.out.println(map);

        System.gc();
        try {
            Thread.currentThread().sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(map);

    }
}

结果:

{key=val}
{}

Process finished with exit code 0

注:从下面ConcurrentReferenceHashMap的部分源码我们可以知道ConcurrentReferenceHashMap是基于Segment分段锁实现的,与JDK1.7的ConcurrentHashMap是一样的,与JDK1.8的ConcurrentHashMap是不一样的。

protected final class Segment extends ReentrantLock {
        private final ConcurrentReferenceHashMap<K, V>.ReferenceManager referenceManager = ConcurrentReferenceHashMap.this.createReferenceManager();
        private final int initialSize;
        private volatile ConcurrentReferenceHashMap.Reference<K, V>[] references;
        private volatile int count = 0;
        private int resizeThreshold;
}
  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值