What is more expensive in Java 1.7 - java.util.concurrent.locks.ReentrantLock or a synchronized block?

Features lock to the side, which one, if any, is more expensive? I could not find any tests.

In situations where special functions are not needed, does Lock have any advantages?

Thanks.

+8
java concurrency
source share
3 answers

This afternoon, a colleague wrote a smart test and found that ReentrantLock is more than twice as fast as synchronized (more than 500 threads performing 60,000 iterations), degrades more slowly and has less GC impact.

In both 1.6 and 1.7 jvms. (In 1.5, synchronized performed much worse)

Sync seems to be great for areas of low competition, but Lock is removing its doors for higher usage.

+3
source share

According to Oracle / David Dice Weblog J2SE 6, 2006 (which I just found through some google search), there is not much difference. Perhaps the situation has changed since then, but I doubt it.

See also the comparison of Lock and ReentrantLock , which contains some benchmarks (and the source code of the template, you can run it on a synchronized ) and eliminates some differences between honest locks and dishonest locks.

One answer to this question: Mixing synchronized () with ReentrantLock.lock () on a reference between different locks when using Copy-on-write collections.

In any case, the most important performance impact is the blocking strategy, i.e. making resources block as short as possible if they form a bottleneck in your application.

+4
source share

Locking has the advantage that you do not need to release the lock in the same method where you get it; you can do things like tryLock() and various other convenient functions that do not have basic synchronization.

+3
source share

All Articles