Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 647
marathon Avatar asked Mar 05 '12 22:03

marathon


2 Answers

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.

like image 135
The Nail Avatar answered Sep 30 '22 07:09

The Nail


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.

like image 25
Louis Wasserman Avatar answered Sep 30 '22 06:09

Louis Wasserman