Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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<Boolean> 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<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();
    }
}
share|improve this question

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.