-1

I have some 75+ requests and each of them are trying to update or access a Map. And If I use Synchronize block of code while updating MAP. Then that might cause performance issues.

Please suggest alternate way to update a MAP, 75+ requests simultaneously.

Note: I am trying to implement the above idea in Java.

deepti mullur
  • 569
  • 1
  • 4
  • 14
  • Well if you want a thread safe map you'll have performance issues, as it cannot be accessed multiple times simultaneously. – BackSlash Apr 11 '17 at 09:58

4 Answers4

1

There are multiple ways to address it, see what suits you best:

SynchronizedMap ConcurrentHashMap

If you use ConcurrentHashMap it will be better for you as the number of requests can increase and you will not see any performance overload. In case of ConcurrentHashMap lock is acquired on specific sections of the ConcurrentHashMap. Which means if two threads are trying to access two different sections separately they can do so without any waiting.

iswan
  • 71
  • 5
1

It is unlikely that 75 or so requests at a time are going to cause any noticeable performance differences between different ways of accessing a Map concurrently. What matters most is simplicity and maintainability of the code. java.util.ConcurrentHashMap is unlikely to show its performance advantages at the scale you're describing, but it's much easier to work with than other solutions, and you will notice that advantage.

Lew Bloch
  • 3,364
  • 1
  • 16
  • 10
0

Try using the concurrent hash map. Basically it divides your hashmap in smaller range and instead of putting the lock on entire map it will have a lock only in smaller range.

If you use synchronized block with hashmap, it will put the lock on complete hashmap and no 2 write operation can be done simultaneously. But if you use concurrent hash map and if you have 2 write operation writing in different range, both can go simultaneously.

Please refer how concurrent hash map works before using it to get better understanding.

Edit :- Please read performance gain of hashmap vs concurrenthashmap in single and multi-threaded application here Performance ConcurrentHashmap vs HashMap.

Community
  • 1
  • 1
Amit
  • 30,756
  • 6
  • 57
  • 88
0

I will add some additional perspective along with the existing answers of ConcurrentHashMap. If many requests are of type read and very few request are update request then you can take a look at java.util.concurrent.locks.ReadWriteLock. It allows multiple threads to read a resource but only one to write it, at a time. If the update requests are multiple then you can use the ConcurrentHashMap as suggested in previous answers

iswan
  • 71
  • 5