8

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.

marathon
  • 7,881
  • 17
  • 74
  • 137
  • Back in 1.5, the synchronized block wasn't as efficient (under certain useful circumstances). In mustang (1.6) AWT changed a not very well encapsulated lock to use `java.util.concurrent.locks`. A couple of weeks later, HotSpot changes were pushed to make it use much the same algorithm for intrinsic locks as jucl uses. – Tom Hawtin - tackline Mar 06 '12 at 00:20

3 Answers3

4

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.

Community
  • 1
  • 1
The Nail
  • 8,355
  • 2
  • 35
  • 48
  • 2
    +1 for short life of locks; because that affects performance, not the kind of lock – Miserable Variable Mar 05 '12 at 23:53
  • 1
    your second link mentions this: "Performance of fair locks is near to synchronized block and non-fair locks is much faster than them." ReentrantLock is non-fair. Anyway, a colleague wrote up something and verified that indeed, a non-fair lock is much faster than synchronized. – marathon Mar 06 '12 at 01:56
3

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.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
3

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.

marathon
  • 7,881
  • 17
  • 74
  • 137
  • 1
    Can you share the benchmark method used (benchmark source code, machine specs)? That would be very interesting. – The Nail Mar 06 '12 at 08:24
  • I wish I could. Anything that gets written here can't be shared for silly legal reasons. – marathon Mar 09 '12 at 01:52