ConcurrentHashMap与基于ReentrantReadWriteLock的自定义地图进行重新加载 [英] ConcurrentHashMap vs ReentrantReadWriteLock based Custom Map for Reloading
问题描述
Java Gurus,
Java Gurus,
当前,我们有一个HashMap<String,SomeApplicationObject>
,它经常被读取并且偶尔被修改,并且在修改/重新加载期间,我们遇到的问题是 Read 操作返回null
这是不可接受的.
Currently we have a HashMap<String,SomeApplicationObject>
which is being read frequently and modified occasionally and we are having issues that during the modification/reloading, Read operation returns null
which is not acceptable.
要解决此问题,我有以下选择:
To fix this I have following options:
A.使用 ConcurrentHashMap
A. Use ConcurrentHashMap
哪个看起来像第一个选择,但是我们要讨论的操作是reload()
-表示clear()
,然后是replaceAll()
.因此,如果在clear()
之后和replaceAll()
之前读取Map
,则返回null,这是不希望的.即使我synchronize
这也不能解决问题.
Which looks like the first choice but the operation which we are talking about is reload()
- means clear()
followed by replaceAll()
. So if the Map
is read post clear()
and pre replaceAll()
it returns null which is not desirable. Even if I synchronize
this doesn't resolves the issue.
B.根据 ReentrantReadWriteLock 创建另一个实现
B. Create another implementation based upon ReentrantReadWriteLock
在reload()
操作之前我将在其中创建获取Write Lock
的位置.这似乎更合适,但是我觉得必须已经有一些可用的东西了,我不需要重新发明轮子.
Where I would create acquire Write Lock
before reload()
operation. This seems more appropriate but I feel there must be something already available for this and I need not to reinvent the wheel.
最好的出路是什么?
编辑?具有该功能的任何收藏集已经可用吗?
EDIT Is any Collection already available with such feature?
推荐答案
似乎您不确定Peter Lawrey建议如何实施.看起来可能像这样:
It seems you are not sure as to how what Peter Lawrey suggests can be implemented. It could look like this:
class YourClass {
private volatile Map<String, SomeApplicationObject> map;
//constructors etc.
public void reload() {
Map<String,SomeApplicationObject> newMap = getNewValues();
map = Collections.unmodifiableMap(newMap);
}
}
没有并发问题,因为:
- 新地图是通过局部变量创建的,根据定义,该局部变量不会共享-
getNewValues
不需要同步或原子化 - 对
map
的分配是原子性的 -
map
是易失性的,它保证其他线程也能看到更改
- The new map is created via a local variable, which by definition is not shared -
getNewValues
does not need to be synchronized or atomic - The assignement to
map
is atomic map
is volatile, which guarantees that other threads will see the change
这篇关于ConcurrentHashMap与基于ReentrantReadWriteLock的自定义地图进行重新加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!