在ConcurrentHashMap中修改值的首选方法是什么? [英] What is the preferred way to modify a value in ConcurrentHashMap?
问题描述
假设我有一个高读,低写的并且需要存储应用程序数据的并发映射:
ConcurrentMap< UUID,Data> map = new ConcurrentHashMap< UUID,Data>();然后,在启动过程中和通过用户输入,数据被添加到地图:
b
$ b
public void createData(Data newData){
map.put(newId,newData); // etc ...
}
如果我需要更改数据, I:
A)使Data类对象不可变,然后在每次需要对Data对象进行更改时执行put操作:
public void changeData(UUID oldId,Foo newInfo){
Data oldData = map.get(oldId);
Data newData = new Data(oldData,newInfo); //仅用于演示的构造函数
map.put(newData);
saveToDatabase(newData);
}
B)使数据类对象可变,原子引用或最终并发字段,并根据需要简单地修改对象:
public void changeData(UUID oldId,Foo newInfo){
数据data = map.get(id);
data.changeSomething(newInfo);
saveToDatabase(data);
}
C)以上都不是
- 因为在你的场景读取更频繁,你应该减少他们的开销量。在此情况下,添加其他同步(例如
volatile
)会对您造成影响。 - 通过使用具有其他自定义保护有bug),你通过使用
ConcurrentHashMap
可以使你的生活变得更容易点。
Let's say I have a Concurrent Map that is high-read, low-write, and needs to store application data:
ConcurrentMap<UUID, Data> map = new ConcurrentHashMap<UUID, Data>();
Then, during startup and through user input, data is added to the map:
public void createData(Data newData) {
map.put(newId, newData); // etc...
}
If I then need to change the data, should I:
A) Make the Data class objects immutable, and then conduct a put operation every time a change is needed for a Data object:
public void changeData(UUID oldId, Foo newInfo) {
Data oldData = map.get(oldId);
Data newData = new Data(oldData, newInfo); // Constructor for demo only
map.put(newData);
saveToDatabase(newData);
}
B) Make the Data class objects mutable yet thread-safe with volatile fields, atomic references or final concurrent fields, and simply modify the object as needed:
public void changeData(UUID oldId, Foo newInfo) {
Data data = map.get(id);
data.changeSomething(newInfo);
saveToDatabase(data);
}
C) None of the above
A) is the better option, for two reasons:
- Since in your scenario reads are more frequent, you should reduce the amount of overhead for them. Adding additional synchronization (such as
volatile
) works against you in this case. - By using mutable objects with additional custom safeguards (which may have bugs) you're pretty much defeating the point of making your life easier by using
ConcurrentHashMap
.
这篇关于在ConcurrentHashMap中修改值的首选方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!