Special features of Lock aside, which one, if either, is more expensive? I couldn't find any benchmarks on this.
For situations where special features are not needed, does Lock have any advantages?
Thanks.
Special features of Lock aside, which one, if either, is more expensive? I couldn't find any benchmarks on this.
For situations where special features are not needed, does Lock have any advantages?
Thanks.
According to Oracle / David Dice's Weblog J2SE 6, 2006 (which I just found through some googling), there's no big difference. Maybe things have changed since then, but I doubt it.
See also this comparison of Lock and ReentrantLock which contains some benchmarks (and source code of the benchmark, you might want to run it on a synchronized
block) and addresses some differences between fair locks and unfair locks.
One answer to this question: Mixing synchronized() with ReentrantLock.lock() links to a benchmark between different locks in using Copy-on-write collections.
Anyway, the most important influence on the performance is your locking strategy, i.e. by making sure you keep resources locked as short as possible if they form the bottleneck of your application.
Lock has the advantage that you don't have to release the lock in the same method where you obtain it; you can do things like tryLock()
, and various other handy features that basic synchronization doesn't have.
A colleague wrote a clever test this afternoon and found that ReentrantLock is more than twice as fast as synchronized (over 500 threads doing 60,000 iterations) ,degrades slower, and has less GC impact.
In both 1.6 and 1.7 jvms. (In 1.5, synchronized performed much worse)
Seems like synchronized is fine for low-contention areas, but Lock blows its doors off for higher contention use.