问题
As explained here: ConcurrentHashMap in Java? concurrent hashmap at Java is thread safe. Java controllers are for web requests and can be called simultaneously from web.
My question is that: Should I use concurrent hash map instead of hash map at Java?
回答1:
You only need a ConcurrentHashMap
if you will be doing concurrent read along with a write or two concurrent writes. If you never change the map after initialization, a regular HashMap
is sufficient.
Controllers should generally not contain any request-specific state (any such state should be passed in to the methods as parameters), and if you design your controllers this way, you shouldn't need any synchronization within your controllers.
回答2:
If you have multiple threads accessing the same hashmap you need to sync this accesss.
You can do that by using an object that has this already implemented like the ConcurrentHashMap or write your own synchronization code and use a plain HashMap.
来源:https://stackoverflow.com/questions/11981743/hashmap-or-concurrenthashmap-at-java-controllers