Skip to content

Instantly share code, notes, and snippets.

@mostafa-asg
Created March 12, 2018 13:13
Show Gist options
  • Save mostafa-asg/72d3b0698816c4a8845d47a4ec6aafcb to your computer and use it in GitHub Desktop.
Save mostafa-asg/72d3b0698816c4a8845d47a4ec6aafcb to your computer and use it in GitHub Desktop.
Spinlock implementation in Java (https://en.wikipedia.org/wiki/Spinlock)
public class SpinLock {
private AtomicReference<Thread> owner = new AtomicReference<Thread>();
public void lock() {
Thread thread = Thread.currentThread();
while (!owner.compareAndSet(null, thread)) {
}
}
public void unlock() {
Thread thread = Thread.currentThread();
owner.compareAndSet(thread, null);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment