Synchronized lock spin

Source: Internet
Author: User

Http://www.jianshu.com/p/5dbb07c8d5d5

Principle

Usually the synchronized is locked on a method or block, where the lock is the object lock (which can also be used on the class), or a weight lock, which is called the object Monitor in the JVM, or the object to monitor the mutex of the thread.

Let's review the logical structure of the object in the heap:


The structure of the object in memory see here "

The structure of the object head is roughly the same:


Where tag 2bit is used to display the lock type. Usually we say that the Synchronized object lock, which is the monitor object when tag=10 here, is the address of this monitor object (which is the weight lock).

When multiple threads request a synchronized method or block at the same time, monitor sets up several virtual logical data structures to manage these multithreading. is a simplified management structure.


The newly requested line routines is first added to the thread queue, the thread is blocked, and when a thread with a lock is unlock, the thread in the queued queue competes (synchronized is an unfair competition lock, as described below). If the running thread calls the object's wait () and then releases the lock and goes to the wait thread collection, the wait thread goes to the queue when the object's notify () or Notifyall () is called. This is the general logic.

And then look at the state diagram of the thread


Blocked is the blocking state.

The biggest difference between wait () and sleep () is that wait () frees the object lock, and sleep () does not! Wait, sleep, yield differences are as follows:


It seems that the synchronized lock and Wait (), notify () to achieve multi-threaded synchronization is complete.

However, spin lock or adaptive spin Lock:

Because the thread blocks into the queued queue and wakes up requires the CPU to switch from a user state to a nuclear mindset, especially frequent blocking and wakeup is a heavy workload for the CPU. At the same time, it is found that the lock state of many object locks will only last for a short period of time, such as a thread switching cycle, so it is obviously not worthwhile to block threads and wake up threads quickly in a short time, so the concept of spin lock is introduced.

The so-called "spin", the monitor does not put the thread block into the queue, but to execute a meaningless loop, after the end of the loop to see if the lock has been released and directly compete in the step, if the competition does not continue spin cycle, The state of the thread in the loop process is always in the running state. The apparent spin lock introduces an unfair approach between threads of the synchronized object lock. However, this ensures a high throughput rate and execution efficiency.

However, although the spin-lock method eliminates the overhead of blocking thread time and space (queue maintenance, etc.), long spins are inefficient. So the number of spins is generally controlled in a range, such as 10,50, after which the thread enters the queued queue.

Adaptive spin Lock is the number of spins that are dynamically adjusted to the upper bound of spin times by the statistics collected by the JVM at runtime.

It seems that the process of synchronized lock is more plump.

However, synchronized is not at the level of the object lock at all times during the run, and it is subject to several escalation changes depending on the thread race situation. There are several other kinds of locks.

light-weight and biased lock

When threads in a multithreaded environment enter the synchronized zone, the JVM does not create object locks immediately, but instead uses a lightweight or biased lock.

However, it is important to be clear that lightweight and biased locks are not a substitute for weight locks, but are no longer necessary to use the weight lock and fearlessly consume resources when there is no multi-threading competition. However, in the event of multi-threaded competition, a lightweight or biased lock in the synchronized area will immediately be upgraded to a weight lock.

A lightweight or biased lock is used when no other thread is in use when entering the synchronized area.

When the thread T accesses the synchronized area of the object, the tag status of the object header is 01, and the 1-bit bias information is used to record whether the object is available for a biased lock. Then T apply for a lightweight lock on the object, if the bias information is 0, indicating that the current object is not locked, or to add a bias lock (plus, note that the object that has been biased to the lock can only be the same line loads lock, if different threads want to acquire the lock, you need to first upgrade the bias lock to a light lock, will be After judging that the current object is indeed not locked by any other thread, you can add a lightweight lock on the object.

The process of adding a lightweight lock is simple: A lock record is generated in the stack frame of the current thread, and the lock record is much simpler than the previous object lock (the monitor that manages the thread queue), which is just a copy of the object's header. Then change the tag in the object header to 00 and put the lock record address in the object header in the stack frame. If the operation is successful, the light-weight lock operation is completed. If this is not successful, the thread is competing, you will need to generate a weight lock on the current object for multi-threaded synchronization, then change the tag state to 10 and generate the monitor object (the weight lock object), and the object header will be placed in the address of the monitor object. Finally, the current thread T is queued in the queue.

The unlocking process of the light-weight lock is also simple to copy the lock record in the stack frame to the object head, if the replacement succeeds, the unlock is complete, if the substitution is unsuccessful, the other thread also competes for the lock during the time the current thread holds the lock, and the lock is upgraded to a weight lock. You need to wake up a thread in the wait queue of monitor to re-compete the lock.

A bias lock is a lightweight locking mechanism that is lighter than a light-weight lock. When the synchronized area is Cheng and unlocked by the same line for a long time, the JVM uses a bias lock, and its locking unlock is simpler than the lightweight lock operation. However, once other threads use the synchronized zone, the bias lock is upgraded to a lightweight lock, even if there is no contention among the threads, and then, of course, the object lock is escalated if there is a thread contention.

Lock Fairness and unfairness: Fair lock refers to the order in which threads acquire locks in accordance with the FIFO principle, first queued first. Unfair locking means that each thread has to compete for the lock first, regardless of the queue order, so the post-to-thread may not need to enter the waiting queue to compete directly to the lock.

While an unfair lock can cause some threads to starve, the rate of lock throughput is fairly locked several times, synchronized is a typical non-fair locking scheme and cannot be made into a fair lock.



Wen/hexter (author of Jane's book)
Original link: http://www.jianshu.com/p/5dbb07c8d5d5
Copyright belongs to the author, please contact the author to obtain authorization, and Mark "book author".

Synchronized lock spin

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.