22

When should we use ReentrantReadWriteLock as compared to synchronized keyword in multithreaded environment in Java?

What are the benefits of using ReentrantReadWriteLock over synchronized in Java?

Can any one give an example as well (in Java)?

Thanks!

informatik01
  • 16,038
  • 10
  • 74
  • 104
Mike
  • 7,606
  • 25
  • 65
  • 82
  • 1
    You may want to read this thread and then see if there is a better way to word your question, as which is better will depend on what you are doing, how your code is accessing objects/variables. http://forum.ragezone.com/f683/synchronised-vs-reentrantlocks-696540/ – James Black Jul 09 '11 at 20:09

3 Answers3

29

Synchronized allows in one thread at a time.

Read/Write locks allow in multiple readers a the same time, but only if no writers are already in. Hence under some usage scenarios we can get better concurrency, because the reader populations can proceed together.

Java API documentation gives the example of collection classes which are expected to have more readers than writers.

informatik01
  • 16,038
  • 10
  • 74
  • 104
djna
  • 54,992
  • 14
  • 74
  • 117
17

The locking article by Brian explains in detail the pros and cons of each approach.

The Lock framework is a compatible replacement for synchronization, which offers many features not provided by synchronized, as well as implementations offering better performance under contention. However, the existence of these obvious benefits are not a good enough reason to always prefer ReentrantLock to synchronized. Instead, make the decision on the basis of whether you need the power of ReentrantLock. In the vast majority of cases, you will not -- synchronization works just fine, works on all JVMs, is understood by a wider range of developers, and is less error-prone. Save Lock for when you really need it. In those cases, you'll be glad you have it.

Gili
  • 86,244
  • 97
  • 390
  • 689
Sanjay T. Sharma
  • 22,857
  • 4
  • 59
  • 71
2

It should be noted that StampedLock has since come out with Java 8, and it's much faster than ReentrantReadWriteLock (especially as you use more and more threads) when you don't use the lock in a reentrant manner (using StampedLock reentrantly can lead to deadlocks, so don't do it).

It also allows optimistic read nonlocks that are available if there is no write lock in effect. Unlike a normal read lock, they don't block a write lock from being established. You can check whether a write lock has been established over your optimistic read nonlock by using the validate method.

Its interface is a little different since you have to store a long value called a stamp in order to later unlock a read or write lock properly or to later validate an optimistic read nonlock properly when you're done.

Chai T. Rex
  • 2,972
  • 1
  • 15
  • 33