CLH Lock的定义:The CLH lock is a scalable, high performance, fairness and spin lock based on the list, the application thread spin only on a local variable, it constantly polling the precursor state, if it is found that the pre release lock end spin.
public class ClhSpinLock implements Lock{
private final ThreadLocal<Node> prev;
private final ThreadLocal<Node> node;
private final AtomicReference<Node> tail = new AtomicReference<Node>(new Node());
public ClhSpinLock() {
this.node = new ThreadLocal<Node>() {
protected Node initialValue() {
return new Node();
}
};
this.prev = new ThreadLocal<Node>() {
protected Node initialValue() {
return null;
}
};
}
public void lock() {
final Node node = this.node.get();
node.locked = true;
Node pred = this.tail.getAndSet(node);
this.prev.set(pred);
// 自旋
while (pred.locked);
}
public void unlock() {
final Node node = this.node.get();
node.locked = false;
this.node.set(this.prev.get());
// this.node.set(new Node());
}
}
CLH 代码分析:
(1)pred node 的作用:其实完全可以把pred node去掉,然后在unlock方法中将this.node 赋值一个新的Node就行。而对this.node赋值prev node,就不用new了,效率更高。
(2)公平锁的体现:通过AtomicReference.getAndSet()将线程形成一个链表.只有等前一个线程释放了锁,后面的线程才能获取锁,确保了锁的公平性。
(3)是否可重入:不能重入,非重入锁。