本文介绍了ConcurrentLinkedHashMap.Builder如何处理删除并获取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用作为 LRUCache ,我很好奇它在 .get >删除键(因为由于其政策,我们最终不得不从 LRUCache 中删除​​键。

I use ConcurrentLinkedHashMap as LRUCache and I'm curious how it handles .get after deletion of a key (because we'll eventually have to remove keys from LRUCache due to its policy.

entityLRUCache = new ConcurrentLinkedHashMap.Builder<GUID, Entity>()
                                            .maximumWeightedCapacity(100)
                                            .build();

...

Entity getEntity(GUID entityId)
{
    if (entityLRUCache.containsKey(entityId))
    {
        // Question: what if key gets deleted from other 
        // thread (when we jumped into this if statement) 
        // and then we'll try to retrieve it here using .get()
        return entityLRUCache.get(entityId);
    }
    else
    {
        Entity entity = longLoadFromDatabase(entityId);
        entityLRUCache.put(entityId, entity);
        return entity;
    }
}

如何使用 ConcurrentLinkedHashMap 类?

谢谢

推荐答案

在这种情况下,您可能要避免从高速缓存中多次读取以避免竞争条件。相反,您可以这样写:

In this case, you would would want to avoid reading multiple times from the cache to avoid race conditions. Instead you would write this as,

Entity getEntity(GUID entityId) {
  Entity entity = entityLRUCache.get(entityId);
  if (entity == null) {
    entity = longLoadFromDatabase(entityId);
    entityLRUCache.put(entityId, entity);
  }
  return entity;
}

在加载要填充的值时,这有一个竞赛,称为缓存踩踏想念。对于该库,如果有问题,可以使用锁定条带化或存储Future来编写装饰器,以避免这种情况。 Google代码Wiki过去提供了一个示例,说明如何编写。

This has a race, called a cache stampede, when loading the value to populate on a miss. For that library, one might write a decorator using lock striping or storing futures to avoid this if problematic. The Google Code wiki used to provide an example of how to write a SelfPopulatingMap.

ConcurrentLinkedHashMap 合并为Guava并演变为。您应该更喜欢该库,您可以在其中编写为,

ConcurrentLinkedHashMap merged into Guava and evolved into Caffeine. You should prefer that library, where you could write this as,

Entity getEntity(GUID entityId) {
  return entityCache.get(entityId, this::longLoadFromDatabase);
}

这篇关于ConcurrentLinkedHashMap.Builder如何处理删除并获取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 09:19