import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.Condition; import java.util.concurrent.TimeUnit; public class MySpinLock implements Lock { private AtomicReference held = new AtomicReference(null); private int count = 0; public void lock() { Thread me = Thread.currentThread(); Thread owner = held.get(); if (owner == me) { count++; return; } // wait until I am the owner while (!held.compareAndSet(null, me)); // now I am the owner count++; return; } public void unlock() { Thread me = Thread.currentThread(); Thread owner = held.get(); if (owner == me) { count--; if (count == 0) held.set(null); return; } // else do nothing } public boolean tryLock() { return false; } public boolean tryLock(long time, TimeUnit unit) { return false; } public Condition newCondition() { return null; } public void lockInterruptibly() throws InterruptedException { throw new InterruptedException(); } }