preface

The synchronized keyword is certainly familiar to Java developers, and we may be comfortable with its usage, but do we really know much about it? Can you talk about it if you go down to the assembly level?

The action and usage of synchronized

Synchronized has long been the elder statesman of multithreaded concurrency, and many would call it the heavyweight lock, but with JDK1.6 making improvements to Synchronized, in some cases it’s not that heavy. Let’s review the role and usage of Synchronized

Role of Synchronized:

(1) Ensure that threads are mutually exclusive access synchronization code

(2) Ensure that the modification of shared variables can be visible in time

(3) Effectively solve the reordering problem

Synchronized usage:

(1) Modify the normal method, lock is the current instance object

public synchronized void add(){System.out.println("Common method synchronization"); }Copy the code

Bytecode instruction

(2) Modify static method, lock is the current Class object

public static synchronized void put(){System.out.println("Static method synchronization"); }Copy the code

Bytecode instruction

(3) Modify the code block, lock is the object configured in Synchronized parentheses

public void set(){synchronized(this){System.out.println("Code block synchronization"); }}Copy the code

Bytecode instruction

Each object has a monitor lock. Monitor is locked when it is occupied.

About method synchronization: The JVM uses this identifier to synchronize methods. When a method is invoked, the calling instruction checks whether the ACC_SYNCHRONIZED access flag of the method is set. If so, The thread of execution retrieves the monitor, executes the method body after the method succeeds, and releases the Monitor after the method completes execution. During method execution, the same Monitor object is no longer available to any other thread.

Synchronization of synchronized blocks: Threads that execute monitorenter try to acquire ownership of monitor, and monitorexit that are blocked by the monitor can attempt to acquire ownership of monitor

Synchronized semantics are implemented through a monitor object, and methods such as Wait /notify also rely on monitor objects, which is why methods such as wait/notify can only be called in Synchronized blocks or methods. Otherwise would be thrown Java. Lang. The cause of the exception IllegalMonitorStateException.

By now we should know that Synchronized is implemented through a lock inside an object called a monitor. But the essence of the monitor Lock depends on the underlying operating system Mutex Lock to implement. However, the operating system realizes the switch between threads, which requires the conversion from user state to core state. This cost is very high, and the conversion between states takes a relatively long time, which is why Synchronized has low efficiency. After JDK1.6, “biased locking” and “lightweight locking” were introduced to reduce the performance cost of acquiring and releasing locks and improve performance.

Java object head

The first part is used to store its own runtime data, such as hash code and GC generation age. It is officially called Mark Word, which is the key to implement lightweight locking and biased locking. Another part is used to execute Pointers to the object type elements of the method area, and an additional part is used to store the length of the array if it is an array. Synchronized locks are stored in Java object headers.

Biased locking

Lock: If a thread acquires a lock, the lock goes into bias mode, and when the thread requests the lock again, it can do any synchronization operation indefinitely. This saves a lot of lock requests and improves program performance. Therefore, in the case of almost no lock contention, biased locking has a better optimization effect, because it is highly likely that the same thread requests the same lock for several consecutive times. However, the effect of lock competition is not good. Because in a competitive situation, it is most likely that a different thread will request the same lock each time. Bias locking is therefore recommended to be turned off in highly competitive applications.

-xx :+UseBiasedLocking Enable partial locking (default)

-xx: -usebiasedlocking Closes the bias lock

Unlock: Biased locks use a mechanism that waits until a race occurs to release the lock, so the thread holding the biased lock will release the lock only when other threads attempt to contest the biased lock.

Lock upgrade: Thread 2 is competing for the lock object, thread 1 still has the bias lock upgrade to lightweight lock.

Lightweight lock

Locking: The JVM will create a space for storing lock records in the current stack frame and copy the Mark Work in the object header into the lock record before the thread executes the synchronized block, which is officially called the product Mark Word. The thread then tries to use CAS to replace the Mark Word in the object header with a pointer that executes the lock record. If it succeeds, the current thread acquires the lock. If it fails, other threads compete for the lock. The current thread attempts to acquire the lock using spin.

(Displaced Mark Word role: in order to don’t want to lock and unlock the add synchronization) on the underlying operating

Unlock: Lightweight unlock will use CAS operation to replace the product of herbier Mark Word back to the object head, if successful, it means that no competition occurs. If it fails, it indicates that a thread is contending for the lock and changes the lock identifier to a heavyweight lock. In this case, the lock is released and the waiting thread is awakened.

Heavyweight lock

If lightweight several times the spin lock can’t lock, competitive, said the current lock, lock will expand into heavy lock, because the spin will consume CPU, to avoid useless spin, once locked upgraded to heavyweight, haven’t been back to lightweight lock state, when the lock is in a state of the other thread will be blocked when trying to acquire the lock, When the thread holding the lock is released, these threads will wake up, and the awakened thread will enter a new round of lock contention.

How to implement synchronized in assembly language?

Do Java people, who does not know horse soldiers?

I still remember ten years ago when I started to learn Java, he was the one who led me into the pit, haha.

Interested friends can get it for free by checking out the blogger’s home page

Let’s go over Mr Ma’s catchphrase again:

“Here, look at my desk.”

“The bean sprouts grow a room high, it is also a vegetable.”

“Ride the donkey to find the horse, but don’t mistreat the donkey, don’t make trouble with the company, the company will not give you a hard time.”

“Class, use your thighs to think about which one is the most… ? Yes, that’s right, everybody’s got big thighs.”

“Vladimir Radmanovic is simply Lenin.”

Teacher Ma’s video is very good, don’t you think?