Deviation lock, lightweight lock, weight-level lock, spin lock principle explanation

Source: Internet
Author: User
Tags cas
First, Introduction

Before we explain these lock concepts, we need to be clear that these locks are not equivalent to Reentratlock locks in the Java API, which are conceptually, the locking mechanisms that are created in JDK1.6 to optimize the synchronized synchronization keyword. The startup and shutdown policies for these locks can be set by setting the JVM startup parameters, and of course, in general, using the JVM default policy.

second, Mark Word in the Java object Header

In hotspot, the Java Object Memory model is divided into three parts, which are the object header, the instance data and the alignment padding respectively. The object header is divided into two parts, one part is Mark Word (which stores the object's own run-time data, 32bit or 64bit, reusable), and the other part is the metadata pointer to its class.

Because synchronized is a built-in lock for a Java object, the information for its optimization strategy (that is, bias locks, etc.) is included in Mark Word, so let's look at the structure of Mark Word first.


(Picture from Network)

One of the most important is the "lock flag bit" and "whether to lock", the lock flag bit represents the state of the current object built-in lock, different lock states, Mark Word store information is different, so called reusable.

third, the bias lock

In layman's terms, the lock is in the running process, the object's lock biased to a certain thread. In the case of turning on the locking mechanism, a thread obtains the lock, and when the thread next wants to acquire the lock, it does not need to acquire the lock (that is, ignore the synchronized keyword), can execute the synchronization code directly, it is more suitable for less competition.

the acquisition process of biased locks:

(1) check mark Word for the identity of the lock and lock flag bit, if the lock is biased to 1 and the lock flag bit is 01, then the lock is a biased state.

(2) If you are biased, test that the thread ID in Word is the same as the current thread, and if the same, execute the synchronization code directly, otherwise go to the next step.

(3) The current thread competes for a lock through a CAS operation, and if the competition succeeds, the mark Word thread ID is set to the current threads ID, and then the synchronization code is executed, and if the competition fails, go to the next step.

(4) When the current thread fails through the CAS competition lock, it indicates a competition. A thread that obtains a preference lock before reaching the global security point is suspended, and the lock is upgraded to a lightweight lock, and then the thread that is blocked at the security point continues to execute the synchronization code.

the release process of biased locks:

Bias lock the thread that holds the lock state will release the lock only if another thread tries to compete for the lock, and the thread does not take the initiative to release the biased lock. A lock-biased revocation needs to wait for a global security point (that is, no bytecode is executing), pausing a thread that has a bias lock, and then returning to the unlocked or lightweight lock state after the revocation.

let's look at an experiment:

/**
 * @author Lee
 * @date 2018/2/8
 * Open bias Lock parameters:-xx:+usebiasedlocking-xx:biasedlockingstartupdelay=0  Time consuming about 4000ms
 * Police bias lock parameters:-xx:-usebiasedlocking time  consuming 1900ms or so/public
class Vectortest {

    public static void Main (string[] args) {
        long time1 = System.currenttimemillis ();
        vector<integer> vector = new vector<integer> ();
        for (int i = 0; i < 100000000 i++) {
            vector.add;//add is synchronized Operation
        }
        System.out.println ( System.currenttimemillis ()-time1);
    }

Because the vector is a synchronization container, the add operation is synchronized decorated, and it is time-consuming to set open biased locks or disable biased locks in JVM parameters, Note that the optimization of the Synchronized keyword in favor of locking is successful in a single thread or in less competitive threads. However, in the case of multithreading competition very frequently, the preference lock can not only improve the efficiency, but also reduce the efficiency because of the constant reset to the thread ID and other consumption. Four, lightweight lock lightweight locks are not used to replace traditional heavyweight locks, but to use lightweight locks to reduce performance consumption when there is no multithreading competition, but when multiple threads compete for locks at the same time, lightweight locks swell into heavyweight locks.

The lock process for lightweight locks:

(1) When the thread executes the code into the synchronization block, if Mark Word is unlocked, the virtual machine first creates a space in the current thread's stack frame called the lock record, which stores the copy of Mark Word for the current object, which is officially called "dispalced Mark Word." , at this point the status is shown below:


(2) Copy the Mark Word in the header of the object to the lock record.

(3) After successful replication, the virtual machine will update the object's Mark Word with the CAS action to execute a pointer to the lock record and point the owner pointer in the lock record to the object's Mark Word. If the update succeeds, 4 is executed, or 5 is performed. ;

(4) If the update succeeds, the thread owns the lock and sets the lock flag to 00, indicating a lightweight lock state, at which point the state diagram:


(5) If the update fails, the virtual opportunity checks whether the object's mark word points to the current thread's stack frame and, if so, indicates that the current thread already owns the lock and can enter the execution synchronization code. Otherwise, when multiple threads compete, lightweight locks swell into heavyweight locks, and Mark Word holds a pointer to a heavyweight lock (a mutex), and a thread that waits for the lock to go into a blocking state.

v. Heavy-weight lock

That is, when another thread occupies a lock, the current thread enters a blocking state. six, Spin lock

In the spin state, when a thread a attempts to enter the synchronized code block, but the current lock is already occupied by thread B, thread A does not enter the blocking state, but instead keeps idling, waiting for thread B to release the lock. If the thread of the lock can release resources in a very short time, then the thread waiting for the competition lock does not need to do the switch between the kernel state and the user state to enter the blocking state, just spin, and so the thread holding the lock can get the lock immediately, to avoid the user thread and the kernel switching consumption.

Spin wait Maximum time : The thread spins will consume the CPU, if the spin too long, it will let the CPU do too much work, so set the spin to wait for the maximum time.

advantages : Open spin lock can reduce the blocking of the thread, in the lock is not competitive and occupy a very short lock time code block, can improve the performance, in this case the spin consumption is less than the thread blocking suspend consumption.

disadvantage : The use of spin will make the CPU do a lot of work without the need for a long time to execute a synchronized block of code while the thread is fiercely locked.

JDK1.6, set the parameter-xx:+usespinning open.

JDK1.7 is automatically controlled by the JVM.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.