简体   繁体   中英

ReentrantReadWriteLock vs synchronized

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!

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM