After stuff like Hashtable and Vector where discouraged, and when the Collections synchronized wrappers came up, I thought synchronization would be handled more efficiently. Now that I looked into the code, I’m surprised that it really is just wrapping the collections with synchronization blocks.
Why are ReadWriteLocks not included into, for example, SynchronizedMap in Collections? Is there some efficiency consideration that doesn’t make it worth it?
Read-write locks are part of performance optimization, which means it can allow greater concurrency in certain situations. The necessary condition is, that they are applied on data structures which are read most of the time, but not modified.
Under other conditions they perform slightly worse than exclusive locks, which comes natural since they have a greater complexity.
It is most efficient, if the locks of a read-write lock are held typically for a moderately long time and only few modifications on the guarded resources.
Hence, whether read-write locks are better than exclusive locks depends on the use case. Eventually you have to measure with profiling which locks perform better.
Taking this into account it seems fitting to choose an exclusive lock for
Collections.synchronizedMapaddressing the general use case instead of the special case with mostly-readers.Further Links
Refactoring Java Programs for Flexible Locking
They wrote a tool which converts locks in a Java application automatically into
ReentrantLocksandReadWriteLockswhere appropriate. For measuring purposes they have also provided some interesting benchmarking results: