HashMap or ConcurrentHashMap at Java Controllers?

限于喜欢 提交于 2019-12-25 05:18:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!