synchronized vs lock vs synchronized map
- I know I can use Synchronize keyword. this is one option. Can I use the map itself ?
- 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.
- I can use a syncronize block
- 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.
精彩评论