Skip to content

Instantly share code, notes, and snippets.

@kylefeng
Created October 10, 2013 08:02
Show Gist options
  • Select an option

  • Save kylefeng/6914708 to your computer and use it in GitHub Desktop.

Select an option

Save kylefeng/6914708 to your computer and use it in GitHub Desktop.

Revisions

  1. kylefeng created this gist Oct 10, 2013.
    37 changes: 37 additions & 0 deletions ClhSpinLock.java
    Original 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;
    }
    }