I wanna a lock in java without happens-before to test other rules of memory visibility. And I've tried Unsafe#compareAndswapInteger
, AtomicInteger#weakCompareAndSet
, they seem still guarantee the happens-before rule?
Here is my test code:
@Test
public void testUnsafeMutex_case2() throws InterruptedException {
class A {
String name;
A(String name) {this.name = name;}
}
class B{A a;}
UnsafeMutex unsafeMutex = new UnsafeMutex();
final B b = new B();
Thread thread = new Thread(() -> {
unsafeMutex.lock();
System.out.println(b.a.name); // **I wanna NPE here**
unsafeMutex.unlock();
});
unsafeMutex.lock(); // put it before Thread#start, and by happens-before rule, it should run first
thread.start();
b.a = new A("name"); // after Thread#start, to avoid happens-before
unsafeMutex.unlock();
thread.join();
}
static class UnsafeMutex {
/**
* no adding key word volatile for avoiding happens before piggy backing
*/
private AtomicInteger state = new AtomicInteger(0);
public void lock() {
while(!state.weakCompareAndSet(0, 1));
}
public void unlock() {
while(!state.weakCompareAndSet(1, 0));
}
}