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.
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).