Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConcurrentHashMap needed with ReadWriteLock?

I have a Map which is read by multiple threads but which is (from time to time) cleared and rebuilt by another thread.

I have surrounded all the access to this map with

readWriteLock.readLock().lock()
try {
  ... access myMap here...
} finally {
  readWriteLock.readLock().unlock()
}

... or the writeLock() equivalents, depending on the type of access.

My question is... will the ReadWriteLock ensure the updates to myMap are visible to the other threads (since they must wait until after the unlock() is called by the writing thread? Or, do I also need to make myMap a concurrent map, like ConcurrentHashMap?

I will probably do that, just to be safe, but I'd like to understand better.

like image 438
Matthew McPeak Avatar asked Aug 02 '19 19:08

Matthew McPeak


People also ask

Do I need ConcurrentHashMap?

ConcurrentHashMap is ideal for high-performance, multi-threaded applications. If you need to access and update a map from multiple threads, ConcurrentHashMap is the best option. It provides all the operations of a HashMap and additionally allows concurrent access for read, write, and update.

Does ConcurrentHashMap in Java use the Readwrite lock?

So unlike hashtable, we perform any sort of operation ( update ,delete ,read ,create) without locking on entire map in ConcurrentHashMap. Retrieval operations (including get) generally do not block. It uses the concept of volatile in this case., so may overlap with update operations (including put and remove).

Which is better to use synchronized over the map or using ConcurrentHashMap?

Concurrent hashmap allows concurrent read and write. So performance is relatively better than a synchronized map. Multiple threads can't access the map concurrently. So, performance is relatively less than a concurrent hash map.

Why HashMap is not used in multi-threaded environment?

Concurrent package. Need of ConcurrentHashmap: Though HashMap has a lot of advantages, it can't be used for multithreading because it is not Thread-safe.


1 Answers

Yes, this should be fine even without a thread-aware map. The Javadoc for ReadWriteLock explicitly says:

All ReadWriteLock implementations must guarantee that the memory synchronization effects of writeLock operations (as specified in the Lock interface) also hold with respect to the associated readLock. That is, a thread successfully acquiring the read lock will see all updates made upon previous release of the write lock.

(Of course, by using a reader/writer lock at all you depend on the map supporting concurrent lookups from different threads. One could imagine clever data structure that try to save time overall by mutating some internal cached state during a lookup. But the standard collections such as HashMap will not do that).

like image 175
hmakholm left over Monica Avatar answered Nov 04 '22 19:11

hmakholm left over Monica