Skip to content

Instantly share code, notes, and snippets.

@kylefeng
Created October 10, 2013 08:02
Show Gist options
  • Save kylefeng/6914708 to your computer and use it in GitHub Desktop.
Save kylefeng/6914708 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() {
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