JVM Biased Locking

from http://arturmkrtchyan.com/jvm-biased-locking

In today’s article I’m going to talk about Biased Locking in jvm. In case you are not familiar with Biased Locking, it’s a technique for improving the performance of uncontended locking.

When Biased Locking is enabled, an object is “biased” toward the thread which first acquires its monitor (locks it) and subsequent acquisitions of the monitor (locking) performed by the same thread are relatively much faster on multiprocessor machines.

There are two main theories behind Biased Locking technique:

  • Most objects are locked by at most one thread during their lifetime.
  • When lock acquisitions are slightly contended the JVM has choices how the lock should be allocated. The lock can be biased toward the thread that most recently acquired the lock. If a thread recently used a lock, the processor’s cache is more likely to still contain data the thread will need the next time it executes code protected by that same lock. If the thread is given priority for re-obtaining the lock, the probability of cache hits increases.

Biased Locking is enabled by default in Java SE 6 and later, to disable it simply add the following option -XX:-UseBiasedLocking to the JVM startup.

Below is an example which you can run to see the benefits of biased locking.

Running without BiasedLocking:

Running with BiasedLocking: (Biased Locking is enabled after 4 minutes, to enable it right away use -XX:BiasedLockingStartupDelay=0 option)

Now you can see the performance benefit yourself.

Notes:

  • When a thread synchronizes on an object that is biased towards another thread, the bias must be revoked by making the object appear as if it had been locked the regular way.
  • The bias is revoked when the identity hash code of an object is accessed since the hash code bits are shared with the thread ID in object header. Currently there’s no space in the mark word to support both an identity hashCode() value as well as the thread ID needed for the biased locking encoding.
  • Objects that are explicitly designed to be shared between multiple threads, such as producer/consumer queues, are not suitable for biased locking. Therefore, biased locking is disabled for a class if revocations for its instances happened frequently in the past.

In summary some applications with significant amounts of uncontended synchronization may attain significant speedups with this flag enabled; some applications with certain amount of contention or patterns of locking may face slowdowns.

For more details read David Dice’s article on Biased Locking in HotSpot

posted @ 2016-03-15 00:48  princessd8251  阅读(476)  评论(0)    收藏  举报