[英]synchronized vs lock vs synchronized map
I need to synchrozize my accesses to the hashmap.我需要同步我对 hashmap 的访问。 Here are my options
这是我的选择
I tend to do 4 cause it sounds the easiest.我倾向于做4,因为这听起来最简单。 Any suggestions?
有什么建议么?
I would suggest that you don't make methods synchronized, and that you don't lock on the map itself.我建议您不要使方法同步,并且不要锁定 map 本身。 I generally prefer to use a separate locking object which is only used for locking and only known about in the class which owns the map.
我通常更喜欢使用单独的锁定 object,它仅用于锁定,并且仅在拥有 map 的 class 中知道。
You could potentially use synchronizedMap
, but it depends what you want to do with it.您可能会使用
synchronizedMap
,但这取决于您想用它做什么。 If you only ever get and put values, then that's fine.如果您只获取和放置值,那很好。 If you ever need to iterate over the map, you need to block other threads from modifying the map while you're iterating.
如果您需要迭代map,则需要在迭代时阻止其他线程修改 map。
Another option is to use a ConcurrentHashMap
.另一种选择是使用
ConcurrentHashMap
。 See the docs for the semantics.有关语义,请参阅文档。 This is probably the simplest approach if it behaves the way you need it to.
如果它的行为方式符合您的需要,这可能是最简单的方法。
You could use ConcurrentHashMap.putIfAbsent() which may do what you want without synchronisation.您可以使用 ConcurrentHashMap.putIfAbsent() 它可以在不同步的情况下执行您想要的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.