上篇我们讲到了自旋锁,在自旋锁中 另有三种常见的锁形式:
TicketLock ,CLHlock 和MCSlock
Ticket锁主要解决的是访问顺序的问题,主要的问题是在多核cpu上
package lock; import java.util.concurrent.atomic.AtomicInteger; public class TicketLock { private AtomicInteger serviceNum =new AtomicInteger(); private AtomicInteger ticketNum = new AtomicInteger(); private static final ThreadLocalLOCAL = new ThreadLocal (); 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); } }
每次都要查询一个serviceNum 服务号,影响性能(必须要到主内存读取,并阻止其他cpu修改)。
CLHLock 和MCSLock 则是两种类型相似的公平锁,采用链表的形式进行排序,
package lock;
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 LOCAL=new ThreadLocal();
private static final AtomicReferenceFieldUpdater UPDATER =AtomicReferenceFieldUpdater.newUpdater(CLHLock.class, CLHNode.class, "tail");
public void lock (){
CLHNode node=new CLHNode();
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是不停的查询前驱变量, 导致不适合在NUMA 架构下使用(在这种结构下,每个线程分布在不同的物理内存区域)
MCSLock则是对本地变量的节点进行循环。不存在CLHlock 的问题。
package lock;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
public class MCSLock {
public static class MCSNode {
volatile MCSNode next;
volatile boolean isLocked = true;
}
private static final ThreadLocal NODE = new ThreadLocal();
@SuppressWarnings("unused")
private volatile MCSNode queue;
private static final AtomicReferenceFieldUpdater 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;
}
}
}
从代码上 看,CLH 要比 MCS 更简单,
CLH 的队列是隐式的队列,没有真实的后继结点属性。
MCS 的队列是显式的队列,有真实的后继结点属性。
JUC ReentrantLock 默认内部使用的锁 即是 CLH锁(有很多改进的地方,将自旋锁换成了阻塞锁等等)。