Java lock Self-rotating lock detailed _java

Source: Internet
Author: User

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

1. Spin Lock

The spin lock is implemented by allowing the current thread to execute continuously in the loop body, which can enter the critical section when the condition of the loop is changed by another thread. As follows

Copy Code code 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);
}
}

Using the CAs atomic operation, 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 forecast value is the current thread.

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

Because the spin lock only keeps the current thread from executing the loop body continuously, the response speed is faster because the thread state is not changed. But when the number of threads keeps increasing, performance drops significantly, because each thread needs to execute, CPU time. If the thread is not competitive and holds the time period of the lock. Suitable to use spin lock.

Note: This example is a non fair lock, and the order of the locks is not carried out in the order of entry lock.

2. Other kinds of spin lock

We've talked about spin locks, and there are three other common types of locks in spin locks: ticketlock, Clhlock and Mcslock.

The main problem with ticket locks is the access order problem, and the main issue is on multi-core CPUs:

Copy Code code 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 you query for a servicenum service number, it affects performance (you must read to the main memory and prevent other CPUs from modifying it).

Clhlock and Mcslock are two similar types of fair locks, sorted by the form of linked lists.

Copy Code code 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 constant query precursor variable that is not suitable for use under NUMA architectures (where each thread is distributed in different physical memory regions)

Mcslock is a loop over the nodes of a local variable. There is no clhlock problem.

Copy Code code 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 perspective, CLH is simpler than MCS,

The CLH queue is an implicit queue, and there is no real successor node attribute.

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

JUC Reentrantlock The default internal use of locks is the CLH lock (there are many improvements, the spin lock replaced by blocking locks, etc.).

(End of full text)

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.