0

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?

Community
  • 1
  • 1
kamaci
  • 72,915
  • 69
  • 228
  • 366

2 Answers2

2

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.

casablanca
  • 69,683
  • 7
  • 133
  • 150
  • Can you give an example just a piece of code there is a controller which needs a concurrent hash map and which needs not? – kamaci Aug 16 '12 at 06:52
  • 1
    @kamaci: As I mentioned, a well-designed controller should not maintain any state and should never require a concurrent hash map. – casablanca Aug 16 '12 at 06:59
0

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.

Daniel Kurka
  • 7,973
  • 2
  • 24
  • 43