Lock implementation using atomics I was recently given an interview and was asked to write my own lock implementation using atomics, but not necessary reentrant.

I didn't answer the question, but at home, I wrote this code. Please asses my implementation and suggest better solutions.

public class MyLock {

    AtomicBoolean locked = new AtomicBoolean(false);

    ThreadLocal&lt;Boolean&gt; threadLocal = new ThreadLocal();

    public void lock() {
        while (true) {
            if (locked.compareAndSet(false, true)) {
                threadLocal.set(true);
                return;
            }
        }
    }

    public void unLock() {
        if (threadLocal.get()) {
            locked.compareAndSet(true, false);
            threadLocal.set(false);
        }
    }

}

class Main {

    public static void main(String[] args) {
        MyLock myLock = new MyLock();
        for (int i=0;i&lt;10;i++)
            new MyThread(myLock).start();
    }
}

class MyThread extends Thread {

    final MyLock myLock;

    MyThread(MyLock myLock) {
        this.myLock = myLock;
    }

    @Override public void run() {
        myLock.lock();
        System.out.println("start - " + Thread.currentThread().getName());
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        System.out.println("finish - " + Thread.currentThread().getName());
        myLock.unLock();
    }
}
I think the main problem of your implementation is that lock() performs Busy waiting. This will cause a thread that is waiting to get the lock to repeatedly waste CPU-cycles by polling (multiple times in one time slot) whether the lock has been released. 

Easiest fix for that is to perform a call to Thread.yield() after trying to acquire the lock. This will cause the thread to exit its time slot and therefore let the other threads do their work.

public void lock() {
    while (true) {
        if (locked.compareAndSet(false, true)) {
            threadLocal.set(true);
            return;
        }
        Thread.yield();
    }
}


Oh and I would rename the method unLock() to unlock() since it is an existing english word.