Created
October 10, 2013 08:02
-
-
Save kylefeng/6914708 to your computer and use it in GitHub Desktop.
Revisions
-
kylefeng created this gist
Oct 10, 2013 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,37 @@ public class ClhSpinLock { private final ThreadLocal<Node> pred; 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.pred = 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.pred.set(pred); while (pred.locked) {} } public void unlock() { final Node node = this.node.get(); node.locked = false; this.node.set(this.pred.get()); } private static class Node { private volatile boolean locked; } }