Search code examples
javathread-safetyhashmapconcurrenthashmap

HashMap or ConcurrentHashMap at Java Controllers?


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?


Solution

  • 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.