Created
October 10, 2013 08:02
-
-
Save kylefeng/6914708 to your computer and use it in GitHub Desktop.
A simple CLH spin lock implementation.
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 characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment