Expansion process and optimization of Java locks

Source: Internet
Author: User
Tags cas

First, the optimization strategy of the lock.

1, Spin lock

The optional lock is actually in the lock when the discovery has been wired to take the lock, if you go to get will block themselves, this time will choose to do a busy cycle attempt. That is, keep looping to see if you can wait until the last thread releases the lock itself. The problem is based on a realistic consideration: many of the threads that take the lock will soon release the lock. Because generally sensitive operations are not much. Of course, this is a situation that can not be fully determined, can only say that the overall is an optimization.

For example, a person who needs to go to the bathroom to find someone in the toilet, he can: 1, wait a little. 2, run to another place to go to the bathroom. Waiting for a small time may not be able to wait for a person to come out, but if you run to other toilets, it will take longer than one person to come out before the result. Of course, the man didn't come out or go to the bathroom somewhere else. This is the slowest.

Then there is an optimization based on this approach: adaptive spin lock. That is, the first set up to spin 10 times, the result of the spin process successfully acquired the lock, then the next time can be set to the maximum spin 20 times. The truth is that if a lock can be released during spin, it is likely that this will happen the next time. Then it is more to give this lock some kind of "convenience" convenient it does not block lock (after all, a lot faster). Similarly, if the result of multiple attempts is completely unable to spin until the release of the lock, then it is very likely that the operation in this critical area is more time consuming. Reduce the number of spins, because the probability is too small.

2, Lock coarsening

Imagine a loop in which there are some sensitive operations in the loop, and some people write the Synchronized keyword in the loop. That's true, but efficiency may be low, as it frequently locks out locks. To know that the lock acquisition (if only the heavyweight mutexlock) is required by the operating system calls, from the user state into the kernel state, the overhead is very high. As a result, it may be possible for the virtual machine to expand the locking range (so called lock coarsening) to avoid frequent lock-release procedures.

3, lock removal

Through the escape analysis found that there is no other thread to compete at all possible (other threads do not have a critical amount of reference), and "self-assertion" to add to their own lock. There is a chance that the virtual opportunity will remove the lock directly.

4, Bias lock and lightweight lock

These two locks are both an optimization strategy and an expansion process so say it together. First of all, their relationship is: the most efficient is to favor the lock, try to use a biased lock, if not (competition) to expand into a lightweight lock, so that the efficiency of the optimization is not as high as the original is still an optimization (compared to the weight lock). So the whole process is optimized as much as possible.

First of all, the bias lock.

Hotspot researchers found that in most cases the lock was added, but there was no competition, and even the same thread repeatedly acquired the lock. Then the lock is biased in order to address this situation.

For example, a warehouse manager with the key, but every time the old king to borrow, warehouse manager so he knew the old king, and he said directly, "OK, you directly take is not to fill out the form I remember you."

Let's talk about the specific process of biased locking. First, the JVM is set to the available bias lock. Then when a process accesses the synchronization block and obtains the lock, it stores the thread ID that obtains the biased lock in the lock record of the object header and the stack frame.

The next time a thread tries to acquire a lock, it first checks that the Markword of the object's header is not the ID that holds it. If so, go straight in without needing any other action. If not, then there are two cases. 1, the object's biased lock flag bit is 0 (not currently biased), indicating that a competition has occurred, has been inflated to a lightweight lock, then the use of CAS operation to try to obtain a lock (this operation is specifically a lightweight lock of the process of acquiring a lock). 2, the bias lock flag bit is 1, indicating or biased lock but the requested thread is not the original one. Just use CAs to try to turn the object head bias lock from the original thread to the thread that is currently seeking the lock. In this case, for example, Lao Wang is retiring and his son takes over his keys, so the warehouse keeper knows his son and his son does not have to register every time he comes.

This CAS failed? First it must be clear why this CAs failed, that is, the competition, there are other threads and it grab lock and win, then in this case, it will require to revoke the bias lock (because of the competition). Then it pauses the thread that has the bias lock first, checks if the thread is an active thread, if not, then you take the lock but not the clerk, the lock also records you, then directly set the object head to a lock-free State again. If it is still an active thread, first traverse the lock record inside the stack frame, let the biased lock become unlocked, and then resume the thread.

Again lightweight lock. This is the product that is biased after the lock expansion.

The process of locking: The JVM Creates a space (Lockrecord) to store the lock record in the stack frame of the current thread, then puts the markword in and generates a pointer to the owner pointing to the locked object. At the same time use CAs to try to markword the object head into a pointer to the lock record. If you succeed, you get the lock. What about the failure? The argument that failed is more. The mainstream is "in-depth understanding of the JVM" and "The Art of concurrent programming".

"In-depth understanding of the JVM," says

Failed to see the value of the Markword. There are 2 possible: 1, pointers to the current thread, 2, and other values.

If it is 1, then the "Re-entry" situation occurs, directly as a success to obtain lock processing.

In fact, this has a question, why the success of the lock and CAS failed, here is actually involved in the specific CAS process: First compare a value is not the predicted value, yes, the use of atomic operation Exchange (or assignment), otherwise, the failure to directly return operation. The value expected when using CAS is its original markword. When the "re-entry" occurs, it will find that the value is not the expected Markword, but a pointer, so of course it will return to failure, but if the pointer points to this thread, then the fact is that the lock has been obtained, but once again entered. If this thread is not, then scenario 2:

If it is 2, then there is competition and the lock expands into a heavyweight lock (Mutexlock)

"The Art of concurrent programming," says:

Failed the direct spin. Expect to acquire a lock in the spin time, if still not available, then start expanding, modify the lock's Markword to a heavyweight lock pointer, and block yourself.

Unlocking process: (the thread that gets the lock) uses the CAs to change the Markword back to the original object head, if successful, then no competition occurs, unlocked complete. If it fails, it means there is a competition (previously wired to attempt to modify Markword through CAs) to release the lock and wake up the blocked thread.

Expansion process and optimization of Java locks

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.