简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM