1

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));
        }
    }
Oleg Osipenko
  • 2,409
  • 1
  • 20
  • 28
onriv
  • 145
  • 1
  • 7
  • 1
    It *doesn't guarantee* happens-before, but that doesn't mean it guarantees "not happens-before". – Kayaman Mar 19 '20 at 15:14
  • @Kayaman Yeah indeed it's. Currently the only way I can use to test memory unvisibility is the nonlocking situation. But many cases are kind of trivial. – onriv Mar 19 '20 at 15:24
  • You'd need input from one of the JVM experts here if there's a chance of getting a working example. I think [this](https://stackoverflow.com/questions/2443239/how-can-weakcompareandset-fail-spuriously-if-it-is-implemented-exactly-like-comp) might be why your code doesn't work as expected. It ends up being a volatile operation, there's a memory fence and you end up with a happens-before anyway. – Kayaman Mar 19 '20 at 15:31
  • 2
    Re, "...to test other rules of memory visibility..." Good luck with that. When the Java Language Spec promises you that your program will behave well if you obey rules X, Y, and Z; that does _not_ mean that your program is guaranteed to behave badly if you _break_ any of those rules. It only means that on some version of the JVM, on some operating system, on some hardware platform, under some conditions, your program is _allowed_ to behave badly. – Solomon Slow Mar 19 '20 at 15:32
  • "they seem still guarantee the happens-before rule?" these rules are written in the specifications. If you want to know the truth, read the spec and do not rely on opinion of random readers. – Alexei Kaigorodov Mar 19 '20 at 18:16

0 Answers0