John Doex
John Doex

Reputation: 21

java ConcurrentHashMap of Integer vs HashMap of AtomicInteger vs ConcurrentHashMap of AtomicInteger

I have doubt regarding concurrent data structure in java, specifically:

1) ConcurrentHashMap<String, Integer>
2) HashMap<String, AtomicInteger>
3) ConcurrentHashMap<String, AtomicInteger>

If I understood correctly:

1) the read/write are thread safe, only one thread can perform an operation of write on one couple (read should be allowed for all thread), so if another thread should modify another couple (different from before) must wait to acquire lock.

2) every thread can access to AtomicInteger value (surely for read), but two threads could modify at the same time different couple of .

3) I think that from a logic point of view is the same of first case

what is the main difference of the three above data structures?

In a multithread situation which every thread should incr/decr the integer value concurrently, what is the best choice ?

Upvotes: 2

Views: 1283

Answers (2)

Shaggy31
Shaggy31

Reputation: 35

ConcurrentHashMap<U,V> and HashMap<U,AtomicInteger> both are synchronized but concurrentHashMap is acquires a lock while HashMap does not.

If using HashMap, multiple threads can read the data together while ConcurrentHashMap will only allow one thread to access the data. Hence it adds the overhead.

Hence if the system needs read and update then HashMap will provide better performance while data consistency can be achieved by both. If system needs to write new data then data consistency can be achieved only by ConcurrentHashMap as it will ensure multiple thread writes are not leading to race condition.

If a system have limited size for map then HashMap<U,AtomicInteger> can be created and initialised with some dummy value upfront. This will ensure in case writes updates are being performed and hence achieving better performance.

Other than that 1 and 3 are similar.

Upvotes: 0

Burak Serdar
Burak Serdar

Reputation: 51632

ConcurrentHashMap is safe to use from multiple threads when you're adding/removing items to/from the map. HashMap is not. Multiple threads can read but only one can write, and during the write no other thread should read.

Having an AtomicInteger as the value of the hashmap allows multiple threads to modify a value already in the map safely.

So: if your map is static (you're not adding/removing anything once you built it), a HashMap with AtomicInteger is safe to use with minimal overhead.

If you add/remove items to/from the map, use a ConcurrentHashMap. If you use Integer, you have to set the value to the map to modify it. If you use AtomicInteger, you can simply set the integer value.

Upvotes: 3

Related Questions