During the interview I was asked the following question:
How to implement an interface Lockif we have all parallel primitives AtomicInteger. That is, no synchronized, volatilevariables java util.concurrent, etc.
Of course, the first thing I thought was something like the following:
public static class ReentrantLock{
private final AtomicInteger locked= new AtomicInteger();
public void lock(){
if(!locked.compareAndSet(0, 1))
}
public void unlock(){
if(!locked.compareAndSet(1, 0))
}
}
But this implementation cannot track Threadwhich acquired the lock. Any ideas how to implement it with just help AtomicInteger? With sun.misc.Unsafeit is possible, but what about without use Unsafe?
The problem is that we cannot track the current thread and change the field lockedatomically.
source
share