使用Java ConcurrentHashMap实现缓存

使用Java ConcurrentHashMap实现缓存,第1张

使用Java ConcurrentHashMap实现缓存

如果为要缓存的内容临时拥有多个实例是安全的,则可以执行“无锁”缓存,如下所示:

public Heavy instance(Object key) {  Heavy info = infoMap.get(key);  if ( info == null ) {    // It's OK to construct a Heavy that ends up not being used    info = new Heavy(key);    Heavy putByOtherThreadJustNow = infoMap.putIfAbsent(key, info);    if ( putByOtherThreadJustNow != null ) {      // Some other thread "won"      info = putByOtherThreadJustNow;    }    else {      // This thread was the winner    }  }  return info;}

多个线程可以“竞争”来创建和添加密钥项,但是只有一个应该“获胜”。



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5462325.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-12
下一篇2022-12-11

发表评论

登录后才能评论

评论列表(0条)

    保存