简体   繁体   English

同步与锁定与同步 map

[英]synchronized vs lock vs synchronized map


I need to synchrozize my accesses to the hashmap.我需要同步我对 hashmap 的访问。 Here are my options这是我的选择

  1. I know I can use Synchronize keyword.我知道我可以使用 Synchronize 关键字。 this is one option.这是一种选择。 Can I use the map itself?我可以使用 map 本身吗?
  2. currently I have a get method that if the object does not exists creates it and puts it in the map.目前我有一个 get 方法,如果 object 不存在,则创建它并将其放入 map。 I can synchronize the method.我可以同步方法。
  3. I can use a syncronize block我可以使用同步块
  4. I can use我可以用
    Map m = Collections.synchronizedMap(new HashMap(...)); Map m = Collections.synchronizedMap(new HashMap(...)); in my code.在我的代码中。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM