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();
}
}
wait()
,notify()
andsynchronized
? \$\endgroup\$