Last active
August 29, 2015 14:08
-
-
Save MichaelScofield/d59b38caa3283efbed74 to your computer and use it in GitHub Desktop.
A simple CLH spin lock implementation
This file contains 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() { | |
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