我想在没有发生之前锁定java来测试内存可见性的其他规则。而且我已经尝试过Unsafe#compareAndswapInteger
,AtomicInteger#weakCompareAndSet
他们似乎仍然保证发生之前的规则?
这是我的测试代码:
@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));
}
}