Java concurrency mechanism and the principle of lock implementation

Source: Internet
Author: User
Tags cas mutex

The basic idea of synchronization

To ensure that shared data is used only by one thread at a time, we have a very simple implementation idea that

A lock is saved in the shared data, and the lock is empty when there is no thread access.

When the first thread accesses, it saves the thread's identity in the lock and allows the thread to access the shared data.

If another thread wants to access the shared data before the current thread releases the shared data, wait for the lock to be released.

    • Save a lock in shared data
    • Save the identity of this thread in the lock
    • Other threads access locked shared data to wait for lock release

Implementation of JVM Synchronization

The following three types of locks are available in the JVM (from top to bottom increasingly "heavyweight"):

    1. Biased lock
    2. Lightweight lock
    3. Heavy-weight lock

Heavy-weight lock

Synchronized principle

We refer directly to the JVM specification as described in: each object has a monitor lock.

When monitor is occupied, it is locked, and the thread attempts to take ownership of the monitor while executing the monitorenter instruction, as follows:

1. If the monitor has an entry number of 0, the thread enters monitor and then sets the entry number to 1, which is the owner of the Monitor.

2, if the thread already occupies the monitor, just re-enter, then enter the monitor into the number plus 1.

3. If another thread has already occupied monitor, the thread goes into a blocking state until the number of incoming monitor is 0, and then tries to get ownership of monitor again.

The semantic bottom of synchronized is done by a monitor object , in fact, wait/notify and other methods also depend on the monitor object,

This is why it is only possible to call wait/notify and other methods in a synchronized block or method, or else the cause of the java.lang.IllegalMonitorStateException exception will be thrown.

Synchronized is implemented by a monitor lock inside the object.

But the nature of the monitor lock is also dependent on the underlying operating system's mutex (mutex lock). and the operating system to implement the switch between the threads that need to transition from the user state to the nuclear mentality, the cost is very high, the transition between States need a relatively long time, which is why the low efficiency of synchronized reasons.

Therefore, this kind of lock that relies on operating system mutexes (mutex lock) is what we call "heavyweight locks".

Lightweight lock

There are four types of locks: lock-free, biased, lightweight, and heavy-lock.

In JDK 1.6, the default is to turn on biased and lightweight locks, and we can also disable biased locks via-xx:-usebiasedlocking.

The core idea of a lightweight lock is that " locked code does not occur concurrently, and if concurrency occurs, it expands into a heavyweight lock (the weight of an expansion-fingered lock rises and is not downgraded once it is upgraded)".

Lightweight locks rely on an operation called CAS (compare and swap).

Term definitions
Terms English Description
Cas Compare and Swap

Compare and set.

Used to provide atomic operations at the hardware level .

In Intel processors, comparisons and exchanges are implemented via the instruction Cmpxchg . Comparisons are consistent with the given values, and if they are consistent, they are not modified.

Biased lock

Based on the implementation of the lightweight lock, we know that while a lightweight lock does not support "concurrency", "concurrency" is inflated to a heavyweight lock, but a lightweight lock can support multiple threads accessing the same lock object in a serial manner.

For example, a thread can get the light lock of the object o First, then a to release the light-weight lock, this time the B-thread to get O's light-weight lock, it can be successfully obtained, in this way can continue serial.

This serial is achieved because there is an action to release the lock. Then suppose there is a lock Java method, this method at run time actually from the beginning to the end only one thread is called, but each call is finished to release the lock, the next call will also regain the lock.

So can we make a hypothesis: "Assuming that the lock code is called from the beginning to the end , if more than one thread is found to be called, then it is not too late to inflate into a lightweight lock." This hypothesis is the core idea that favors the lock.

A biased lock relies on an operation called CAS (compare and swap).

Summarize

This paper focuses on the optimization of synchronized using lightweight lock and biased lock in JDK,

But these two kinds of locks are not completely no shortcomings, such as competition is more intense, not only can not improve efficiency, but will reduce efficiency, because more than a lock upgrade process, this time will need to-xx:-usebiasedlocking to disable the biased lock. Here are the comparison of these types of locks:

Lock

Advantages

Disadvantages

Applicable scenarios

Biased lock

Locking and unlocking does not require additional consumption, and the execution of a non-synchronous method is less than the nanosecond-level gap.

If there is a lock contention between threads, additional lock revocation consumption is brought.

Applies to only one thread to access the synchronization block scenario.

Lightweight lock

The competing threads do not block, increasing the responsiveness of the program.

If a thread that does not have a lock contention is always using spin, it consumes the CPU.

The pursuit of response time .

Synchronization blocks execute very quickly.

Heavy-weight lock

Thread contention does not use spin and does not consume CPU.

The thread is blocked and the response time is slow.

Pursuit of throughput .

The synchronization block executes more slowly.

Refer to the following:

51932179

Java concurrency mechanism and the principle of lock implementation

Related Article

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.