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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With