Add demo for CLH
This commit is contained in:
parent
33b6dc149d
commit
0faf89f006
30
src/main/java/threaddemo/lock/CLH.java
Normal file
30
src/main/java/threaddemo/lock/CLH.java
Normal 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());
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user