Skip to content

Instantly share code, notes, and snippets.

@MichaelScofield
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MichaelScofield/d59b38caa3283efbed74 to your computer and use it in GitHub Desktop.
Save MichaelScofield/d59b38caa3283efbed74 to your computer and use it in GitHub Desktop.
A simple CLH spin lock implementation
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() {
node = new ThreadLocal<Node>() {
protected Node initialValue() {
return new Node();
}
};
pred = new ThreadLocal<Node>() {
protected Node initialValue() {
return null;
}
};
}
public void lock() {
final Node node = this.node.get();
node.status = Node.STATUS.LOCKED;
Node pred = tail.getAndSet(node);
this.pred.set(pred);
//noinspection StatementWithEmptyBody
while (pred.status != Node.STATUS.LOCKED) {}
}
public void unlock() {
final Node node = this.node.get();
node.status = Node.STATUS.RELEASED;
this.node.set(pred.get()); // gc friendly
}
static class Node {
static enum STATUS {
RELEASED, LOCKED
}
volatile STATUS status;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment