当前位置: 动力学知识库 > 问答 > 编程问答 >

is that thread safe to update entry.value.field directly in ConcurrentHashMap?

问题描述:

Sometimes, we need to update one field of entry.value.

the thread safe way to do that is construct a new entry.value and

use put method to update. that is said, I need to make deep copy

of original value even though I just do some little modification.

Can I do this update like

map[key].field = fieldValue;

网友答案:

Hash map returns an entry safely, but assignment of a field is out of scope of the map. So, you should do something here for thread safety. Your code is equivalent to:

Entry entry = map[key];
entry.field = fieldValue;

Obviously the field assignment operator doesn't know anything about the map.

网友答案:

Maybe a lock for the entry itself is needed. If it is just an assignment, then volatile.

分享给朋友:
您可能感兴趣的文章:
随机阅读: