parallele-programmierung/u06-5/SpinLock.java

20 lines
482 B
Java

import java.util.concurrent.atomic.AtomicReference;
class SpinLock {
private AtomicReference<Thread> currentThread;
public SpinLock() {
currentThread = new AtomicReference<Thread>(null);
}
public void lock() {
Thread thisThread = Thread.currentThread();
// wait for currentThread to be null to acquire lock
while (!currentThread.compareAndSet(null, thisThread));
}
public boolean unlock() {
return currentThread.compareAndSet(Thread.currentThread(), null);
}
}