Reputation: 2596
I'm reading the documentation about ReadWriteLock
Whether or not a read-write lock will improve performance over the use of a mutual exclusion lock depends on the frequency that the data is read compared to being modified, the duration of the read and write operations, and the contention for the data - that is, the number of threads that will try to read or write the data at the same time.
What does "mutual exclusion lock" mean? Does it mean that we can perform only one operation (reading or writing) at a time? For instance, just a synchronized block.
Upvotes: 1
Views: 137
Reputation: 919
A mutual exclusion lock will ensure that only one operation can be performed at a time (one reader or one writer).
According to the javadoc of ReadWriteLock
:
The read lock may be held simultaneously by multiple reader threads, so long as there are no writers. The write lock is exclusive.
In practice this means that if you have a large number of writers, then it becomes hard for the readers to gain access as a single writer will lock out all readers. Alternatively, if you have many readers performing short reads then the overhead of the ReadWriteLock
will perform worse than a simple mutual exclusion lock as the ReadWriteLock
has a much greater overhead.
I have paraphrased this section of the javadoc:
For example, a collection that is initially populated with data and thereafter infrequently modified, while being frequently searched (such as a directory of some kind) is an ideal candidate for the use of a read-write lock. However, if updates become frequent then the data spends most of its time being exclusively locked and there is little, if any increase in concurrency. Further, if the read operations are too short the overhead of the read-write lock implementation (which is inherently more complex than a mutual exclusion lock) can dominate the execution cost, particularly as many read-write lock implementations still serialize all threads through a small section of code
Upvotes: 3