我正在尝试使用 Google Guava Cache 制作 ConcurrentHashMaps 的线程安全单例缓存。这些地图中的每一个都将包含一个列表。列表只会在所有可以添加到它的线程都执行后被读取一次。我想知道我的实现(特别是在我更新项目的地方)是否是线程安全的/如何改进它。有没有更好的方法可以在不使用同步块的情况下做到这一点?
public enum MyCache {
INSTANCE;
private static Cache<Integer, ConcurrentHashMap<String, List>> cache =
CacheBuilder.newBuilder()
.maximumSize(1000)
.build();
private static AtomicInteger uniqueCount = new AtomicInteger(0);
private final Object mutex = new Object();
//Create a new unique ConcurrentHashMap
public Integer newMapItem(){
Integer key = uniqueCount.incrementAndGet();
//We dont care if something exists
cache.put(
key,
new ConcurrentHashMap<String, List>()
);
return key;
}
public void expireMapItem(int key){
cache.invalidate(key);
}
public Integer add(int cacheKey, String mapListKey, int value){
synchronized(mutex){
ConcurrentMap<String, List> cachedMap = cache.getIfPresent(cacheKey);
if (cachedMap == null){
//We DONT want to create a new map automatically if it doesnt exist
return null;
}
List mappedList = cachedMap.get(mapListKey);
if(mappedList == null){
List newMappedList = new List();
mappedList = cachedMap.putIfAbsent(mapListKey, newMappedList);
if(mappedList == null){
mappedList = newMappedList;
}
}
mappedList.add(value);
cachedMap.replace(mapListKey, mappedList);
cache.put(
cacheKey,
cachedMap
);
}
return value;
}
}