Java multithreading-4-LOCK

Four, LOCK

1. The 4 states of the lock

[1] Optimization of lock

In order to reduce the performance cost of acquiring and releasing locks, JDK6 introduced "biased locks" and "lightweight locks"

As a result, the lock has 4 states, which will be upgraded with lock competition. The lock can be upgraded but not downgraded. The upgrade of the lock is called "lock expansion"

[2] Partial lock state

In most cases, the lock not only does not have multi-thread competition, but also is always acquired by the same thread multiple times

In order to improve the performance of this situation, a bias lock is introduced

The thread ID of the lock bias is stored in the lock record in the object header and the stack frame. When a thread enters and exits the synchronization block, it does not need to perform CAS operations to lock and unlock, and directly determine whether there is a Mark Word in the object header Point to the bias lock of the current thread

If it exists, the thread has acquired the lock, if it does not exist, the lock is expanded to a lightweight lock

The bias lock is enabled by default in JDK6 and JDK7, but it needs to be activated a few seconds after the program starts

If you need to turn off this delay, use the JVM parameter

-XX:BiasedLockingStartupDelay=0

If you turn off the bias lock, use the JVM parameter

-XX:-UseBiasedLocking

[3] Lightweight lock status

Locking: The JVM creates a space for storing the lock mark in the stack frame of the current thread, and copies the Displaced Mark Word in the object header to it. If it succeeds, it means that the current thread acquires the lock successfully. If it fails, it means there is lock competition. The current thread will try to use spin to acquire the lock.

Unlock: Use atomic CAS operation to replace Displaced Mark Word back to the object head. If it succeeds, it means that there is no lock competition. If it fails, it means that there is lock competition, which will cause the lock to expand into a heavyweight lock.

[4] Contrast

Lock type advantage Disadvantage Applicable scene
Bias lock There is no additional waiting for locking and unlocking,
and there is a nanosecond difference (1 nanosecond = 1000 * 1000 milliseconds) compared with the lock-free execution method
If there is lock competition, it
will bring additional consumption of revocation locks
Only one thread accesses the synchronized block
Lightweight lock Competing threads will not be blocked, which
improves the response speed of the program
If the thread has not been able to acquire the lock,
using spin will consume CPU
The pursuit of response speed, the
synchronization block execution speed is very fast
Heavyweight lock Thread competition does not use spin and does not consume CPU Competing threads will block, which
will reduce response speed
Pursue throughput, synchronous block execution time is longer

2. Fair lock and unfair lock

Fair lock: When each thread acquires a lock, it first checks the waiting queue maintained by the lock. If the queue is empty or the current thread is the first (head) in the queue, the thread acquires the lock. In the future, I will be retrieved from the waiting queue according to the FIFO principle (queue to wait to acquire the lock)

Unfair lock: every thread can try to acquire the lock

synchronized is an unfair lock

java.util.concurrent.locks.ReentrantLock is an unfair lock created by a parameterless constructor. Pass a parameterized constructor and pass true, the lock is a fair lock

3. Reentrant lock

Reentrant locks are also called recursive locks , which refer to threads that have acquired the lock. When executing the synchronization method in the synchronization method, the method can be executed directly without acquiring the lock again

synchronized and java.util.concurrent.locks.ReentrantLock are reentrant locks

4. Spin lock

Threads try to acquire locks by spinning to reduce the overhead of thread context switching

class CasLock {
    
    
    private final AtomicReference<Thread> reference = new AtomicReference<Thread>();

    public void lock() {
    
    
        for (;;) {
    
    
            if (tryAcquire()) {
    
    
                break;
            }
        }
    }

    public void unlock() {
    
    
        for (;;) {
    
    
            if (tryRelease()) {
    
    
                break;
            }
        }
    }

    private boolean tryAcquire() {
    
    
        Thread thread = Thread.currentThread();
        return reference.compareAndSet(null, thread);
    }

    private boolean tryRelease() {
    
    
        Thread thread = Thread.currentThread();
        return reference.compareAndSet(thread, null);
    }

}

5. Shared locks and exclusive locks

Shared lock: multiple threads can acquire the lock

Exclusive lock: the lock can only be exclusive to one thread

The read lock of java.util.concurrent.locks.ReentrantReadWriteLock is shared by threads, while the write lock is exclusive by threads

synchronized and java.util.concurrent.locks.ReentrantLock are exclusive locks

6. Read-write lock

java.util.concurrent.locks.ReentrantReadWriteLock

Read-write lock, read lock and write lock coexist, read lock shared, write lock exclusive

7. Thread compatibility and thread opposition

Thread compatibility: The object to be manipulated is not thread-safe, but various thread-safe methods can be used to ensure that the operating object is thread-safe in a multi-threaded environment.

Thread opposition: The object to be operated is thread-safe, but because the concurrent request of multiple threads is not thread-safe when the object is operated in a multi-threaded environment, the operation object itself becomes thread-unsafe

Examples of the Java-hostile line: Thread class method of disposal (@Deprecated) suspendand resumemay cause a deadlock

Guess you like

Origin blog.csdn.net/adsl624153/article/details/103865288