开发者

synchronized vs lock vs synchronized map

I need to synchrozize my accesses to the hashmap. He开发者_开发问答re are my options

  1. I know I can use Synchronize keyword. this is one option. Can I use the map itself ?
  2. currently I have a get method that if the object does not exists creates it and puts it in the map. I can synchronize the method.
  3. I can use a syncronize block
  4. I can use

    Map m = Collections.synchronizedMap(new HashMap(...)); in my code.

I tend to do 4 cause it sounds the easiest. Any suggestions?


I would suggest that you don't make methods synchronized, and that you don't lock on the map itself. 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.

You could potentially use synchronizedMap, but it depends what you want to do with it. 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.

Another option is to use a 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜