Add demo for CLH

This commit is contained in:
= 2025-03-16 22:09:58 +08:00
parent 33b6dc149d
commit 0faf89f006

View File

@ -0,0 +1,30 @@
package threaddemo.lock;
import java.util.concurrent.atomic.AtomicReference;
/**
* demo class for CLH. code from
* <a href="https://mp.weixin.qq.com/s/jEx-4XhNGOFdCo4Nou5tqg">Java AQS 核心数据结构-CLH </a>
* This is only for demo, do not run the code this node class is not workable
*/
public class CLH {
private final ThreadLocal<Node> node = ThreadLocal.withInitial(Node::new);
private final AtomicReference<Node> 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());
}
}