SoFunction
Updated on 2025-04-11

How to use synchronized in Java and lock upgrade

In Java concurrent programming,synchronizedIt is a very important keyword, used to implement thread synchronization, ensuring that only one thread can access the synchronized code block or method at the same time, thereby avoiding data inconsistency caused by multi-threading. At the same time, Java Virtual Machine (JVM) is to improveynchronizedThe performance of the lock upgrade mechanism is introduced. Let's introduce it in detail belowynchronizedand lock upgrade process.

1. How to use synchronized

(I) Ordinary method of modifying

whensynchronizedWhen modifying a normal method, the lock object is the current object (this). That is to say, when a thread enters this method, the lock of the current object will be automatically acquired. If other threads want to enter this method, they must wait for the current thread to release the lock. For example:

public class SynchronizedExample {
    public synchronized void synchronizedMethod() {
        // Code logic for thread synchronization        ("Thread" + ().getName() + "Enter the synchronization method");
        try {
            (2000);
        } catch (InterruptedException e) {
            ();
        }
        ("Thread" + ().getName() + "Exit synchronization method");
    }
}

In the above code,synchronizedMethodIt is a synchronous method. When multiple threads call the method at the same time, they will queue up to execute it in sequence, ensuring the thread safety of the code in the method.

(II) Modify static methods

whensynchronizedWhen modifying a static method, the lock object is of this class.ClassObject. Because static methods are class-level and do not depend on specific object instances, the class'sClassObjects act as locks. Examples are as follows:

public class StaticSynchronizedExample {
    public static synchronized void staticSynchronizedMethod() {
        ("Thread" + ().getName() + "Enter static synchronization method");
        try {
            (2000);
        } catch (InterruptedException e) {
            ();
        }
        ("Thread" + ().getName() + "Exit static synchronization method");
    }
}

Multiple thread callsstaticSynchronizedMethodWhen the class will beClassThe object is locked to achieve thread synchronization.

(III) Modify the code block

synchronizedYou can also modify the code block, and you need to explicitly specify the lock object. The lock object can be any object, as long as the same lock object is guaranteed to be used in the code block that needs to be synchronized. for example:

public class BlockSynchronizedExample {
    private Object lock = new Object();
    public void blockSynchronized() {
        synchronized (lock) {
            ("Thread" + ().getName() + "Enter the synchronous code block");
            try {
                (2000);
            } catch (InterruptedException e) {
                ();
            }
            ("Thread" + ().getName() + "Exit the Synchronous Code Block");
        }
    }
}

In this example,lockObjects are locks for synchronous code blocks, accessed by multiple threadsblockSynchronizedWhen the method is done, there will be competitionlockThe lock of the object.

2. Synchronized lock upgrade

To improvesynchronizedThe performance of JVM introduces a lock upgrade mechanism, starting from the lock-free state, gradually upgraded to biased locks, lightweight locks and heavyweight locks according to competition conditions.

(1) Lockless

The lock-free state is the most basic state. When there is no thread competing for the lock, the object is in the lock-free state. At this time, the thread can directly access thesynchronizedThe modified code does not require any locking operation, so it performs the highest performance.

(II) Positive lock

When a thread is accessed for the first timesynchronizedWhen modifying the code, the JVM will set the lock flag in the object header to bias lock mode and record the thread's ID in the object header. After that, when the thread accesses the synchronization code of the same object again, there is no need to perform an additional lock operation and directly enters the synchronization code block, because the JVM believes that the thread will likely access it again. The existence of biased locks reduces the overhead of locks in the absence of competition.

(III) Lightweight lock

When a second thread tries to access the synchronization code of the same object, the bias lock is upgraded to a lightweight lock. The JVM creates a lock record in the stack frame of the current thread and copies the Mark Word in the object header to the lock record, and then tries to replace the Mark Word in the object header with a pointer to the lock record using the CAS (Compare - And - Swap, Compare and Swap) operation. If the CAS operation is successful, the current thread will obtain a lightweight lock and can enter the synchronous code block; if it fails, it means there is competition, and the lightweight lock will be upgraded to a heavyweight lock.

(IV) Heavyweight lock

When the lightweight lock competition fails, that is, multiple threads compete for the lock at the same time, it will be upgraded to a heavyweight lock. At this time, the JVM will use the operating system's mutex (Mutex) to implement the locking mechanism, and the thread will enter a blocking state, waiting for the lock to be released. The performance of heavyweight locks is relatively low because thread blocking and wake-up requires the intervention of the operating system, which will bring greater overhead.

The lock upgrade process is dynamically adjusted by the JVM based on actual thread competition situations. The purpose is to ensure thread safety while improving it as much as possible.synchronizedperformance.

Anyway,synchronizedIt is an important means to implement thread synchronization in Java concurrent programming. Understanding its usage method and lock upgrade mechanism is of great significance to writing efficient and safe multi-threaded programs. In actual development, we should use it reasonably according to specific scenariossynchronized, and pay attention to the granularity and performance optimization of the lock to give full play to the advantages of multi-threading.

This is the end of this article about the use of synchronized in Java and lock upgrade. For more related content on Java synchronized, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!