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.
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.
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).
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With