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.
Blocking locks
Blocking locks, unlike spin locks, change the running state of a thread.
In the Java environment, thread threads have several states:
1, new state
2, Ready state
3, running status
4, blocking state
5, the state of death
Blocking the lock, it can be said that the thread into the blocking state of waiting, when the corresponding signal (wake-up, time), can enter the ready state of the thread, ready state of all the threads, through competition, into the running state.
In Java, the ability to enter \ Exit, block state, or include blocking locks is available in the Synchronized keyword (where the weight lock), reentrantlock,object.wait () \notify (), Locksupport.park ()/ Unpart () (j.u.c often used)
Here is a Java blocking lock instance:
Package lock;
Import Java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
Import Java.util.concurrent.locks.LockSupport;
public class CLHLock1 {public static class Clhnode {private volatile Thread islocked;
@SuppressWarnings ("unused") private volatile clhnode tail;
Private static final threadlocal<clhnode> local = new threadlocal<clhnode> (); Private static final Atomicreferencefieldupdater<clhlock1, clhnode> updater =
Atomicreferencefieldupdater.newupdater (Clhlock1.class, Clhnode.class, "tail");
public void Lock () {clhnode node = new Clhnode ();
Local.set (node);
Clhnode Prenode = Updater.getandset (this, node);
if (Prenode!= null) {prenode.islocked = Thread.CurrentThread ();
Locksupport.park (this);
Prenode = null;
Local.set (node);
} public void Unlock () {clhnode node = Local.get (); if (!updater.compareaNdset (this, node, null)) {System.out.println ("unlock\t" + node.isLocked.getName ());
Locksupport.unpark (node.islocked);
node = null;
}
}
Here we use the blocking lock of the Locksupport.unpark (). The example is to modify the CLH lock.
The advantage of blocking locks is that blocked threads do not consume CPU time and do not cause high CPU usage, but are slower to enter and recover time than spin locks.
In the case of intense competition, the performance of blocking locks is significantly higher than that of spin locks.
The ideal situation is; In the case of online competition, the use of spin locks, the competition in the case of intense use, blocking locks.
(End of full text)