Creating a simple TTAS (test, test and set) spin-lock is fairly trivial:
class TTASLock {
private final AtomicLong thread = new AtomicLong();
void lock() {
while (true) {
if (thread.get() == 0) { // test
if (thread.compareAndSet(0, Thread.currentThread().getId())) // testAndSet
return;
}
}
}
void unlock() {
thread.compareAndSet(Thread.currentThread().getId(), 0)
}
}
This is a very simple spin-lock. The test, test and set paradigm is not strictly necessary from a logical pov, but is a critical performance improvement so that under contention a thread awaiting lock acquisition is not continually invalidating the Level2 cache line with failed CAS ops.