package threaddemo.lock; import java.util.concurrent.atomic.AtomicReference; /** * demo class for CLH. code from * Java AQS 核心数据结构-CLH 锁 * This is only for demo, do not run the code this node class is not workable */ public class CLH { private final ThreadLocal node = ThreadLocal.withInitial(Node::new); private final AtomicReference tail = new AtomicReference<>(new Node()); private static class Node { private volatile boolean locked; } private void lock() { Node node = this.node.get(); node.locked = true; Node pre = this.tail.getAndSet(node); while (!pre.locked) ; } private void unlock() { final Node node = this.node.get(); node.locked = false; this.node.set(new Node()); } }