Java Lock spin Lock explanation

Source: Internet
Author: User

Lock as a tool for concurrent shared data, ensuring consistency, there are many implementations in the Java platform (such as synchronized and Reentrantlock, etc.). These locks have been written to provide convenience for our development, but the specific nature and type of the lock are rarely mentioned. This series of articles will analyze common lock names and features in Java to help you answer questions.

1. Spin Lock

A spin lock is implemented in a loop in which the current thread is continuously executing, and can enter the critical section when the condition of the loop is changed by another thread. As follows

Copy CodeThe code is as follows:
public class SpinLock {

Private atomicreference<thread> sign =new atomicreference<> ();

public void Lock () {
Thread current = Thread.CurrentThread ();
while (!sign. Compareandset (null, current)) {
}
}

public void unlock () {
Thread current = Thread.CurrentThread ();
Sign. Compareandset (current, null);
}
}

With CAS atomic operations, the lock function sets owner to the current thread and predicts that the original value is empty. The Unlock function sets owner to NULL, and the predicted value is the current thread.

When a second thread calls the lock operation because the owner value is not NULL, the loop is always executed until the first thread calls the Unlock function to set the owner to NULL, and the second thread can enter the critical section.

Because the spin lock simply keeps the current thread executing the loop body without changing the thread state, the response is faster. However, when the number of threads increases continuously, performance degrades significantly because each thread needs to execute, consuming CPU time. If the thread is not competing fiercely, and the time period of the lock is maintained. Suitable for use with spin locks.

Note: This example is an unfair lock, and the order in which the locks are obtained is not carried out in the order in which they enter lock.

2. Other types of spin locks

We talked about spin locks, and there are three other common types of locks in the spin lock: Ticketlock, Clhlock and Mcslock

Ticket locks primarily address the problem of access order, the main problem is on multicore CPUs:

Copy CodeThe code is as follows:
Package com.alipay.titan.dcc.dal.entity;

Import Java.util.concurrent.atomic.AtomicInteger;

public class Ticketlock {
Private Atomicinteger Servicenum = new Atomicinteger ();
Private Atomicinteger Ticketnum = new Atomicinteger ();
private static final threadlocal<integer> LOCAL = new threadlocal<integer> ();

public void Lock () {
int myticket = Ticketnum.getandincrement ();
Local.set (Myticket);
while (Myticket! = Servicenum.get ()) {
}

}

public void unlock () {
int myticket = Local.get ();
Servicenum.compareandset (Myticket, Myticket + 1);
}
}

Each time a Servicenum service number is queried, it affects performance (it must be read to main memory and block other CPU modifications).

Clhlock and Mcslock are two types of similar fair locks, sorted in the form of a linked list.

Copy CodeThe code is as follows:
Import Java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

public class Clhlock {
public static class Clhnode {
Private volatile Boolean isLocked = true;
}

@SuppressWarnings ("unused")
private volatile clhnode tail;
private static final threadlocal<clhnode> LOCAL = new threadlocal<clhnode> ();
Private static final Atomicreferencefieldupdater<clhlock, clhnode> UPDATER = Atomicreferencefieldupdater.newupdater (Clhlock.class,
                                                                                       clhnode.class, "tail");

    public void Lock () {
        clhnode node = new Clhnode (); br>        local.set (node);
        Clhnode Prenode = Updater.getandset (this, node);
        if (prenode! = null) {
             while (prenode.islocked) {
            }
            prenode = null;
            local.set (node);
       }
   }

public void unlock () {
Clhnode node = Local.get ();
if (!updater.compareandset (this, node, null)) {
node.islocked = false;
}
node = null;
}
}

Clhlock is a non-stop query precursor variable that is not suitable for use in a NUMA architecture (where each thread is distributed in a different physical memory area)

Mcslock is the loop of the nodes of the local variable. There is no problem with Clhlock.

Copy CodeThe code is as follows:
Import Java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

public class Mcslock {
public static class Mcsnode {
Volatile Mcsnode next;
Volatile Boolean isLocked = true;
}

private static final threadlocal<mcsnode> NODE = new threadlocal<mcsnode> ();
@SuppressWarnings ("unused")
private volatile mcsnode queue;
Private static final Atomicreferencefieldupdater<mcslock, mcsnode> UPDATER = Atomicreferencefieldupdater.newupdater (Mcslock.class,
Mcsnode.class, "queue");

public void Lock () {
Mcsnode CurrentNode = new Mcsnode ();
Node.set (CurrentNode);
Mcsnode Prenode = Updater.getandset (this, currentnode);
if (Prenode! = null) {
Prenode.next = CurrentNode;
while (currentnode.islocked) {

}
}
}

    public void Unlock () {
        mcsnode CurrentNode = Node.get ();
        if (currentnode.next = = null) {
             if (Updater.compareandset (this, currentnode, null)) {

} else {
while (Currentnode.next = = null) {
}
}
} else {
currentNode.next.isLocked = false;
Currentnode.next = null;
}
}
}

From the code, CLH is much simpler than MCS,

The CLH queue is an implicit queue with no real successor attributes.

The MCS queue is an explicit queue with a real successor node attribute.

JUC Reentrantlock The lock that is used internally by default is the CLH lock (there are many improvements where the spin lock is replaced with a blocking lock, and so on).

(End of full text)

Java lock spin lock detailed

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.