import java.util.concurrent.atomic.AtomicReference; class SpinLock { private AtomicReference currentThread; public SpinLock() { currentThread = new AtomicReference(null); } public void lock() { Thread thisThread = Thread.currentThread(); // wait for currentThread to be null to acquire lock while (!currentThread.compareAndSet(null, thisThread)); } public boolean unlock() { return currentThread.compareAndSet(Thread.currentThread(), null); } }