Java concurrency problem

  public class Apple {
    public int a = 0;
    public Apple() {
        for (int i = 0; i < 50000; iPP) {
            a = i;
        }
    }
}
public class SimpleCounter {
    Apple apple;
//   volatile Apple apple;

    public void setApple() {
        apple = new Apple();
    }

    public Apple getApple() {
        while (true) {
            if (null != apple) {
                return apple;
            }
        }
    }
}
@RunWith(ConcurrentTestRunner.class)
public class TestSimpleCounter {
    private SimpleCounter simpleCounter = new SimpleCounter();
    @Test
    public void testSetApple() {
        simpleCounter.setApple();
    }
    @Test
    public void testGetApple() {
        System.out.println(simpleCounter.getApple().a);
    }
}

Why can"t the above code stop running? just change it to volatile, testing the concurrent-junit used by the framework.

May.07,2022

it's probably a memory visibility issue

when doing nothing (no volatile, no lock, etc.), JVM does not guarantee that one thread can read the writes of other threads


it is recommended to post the code or library directly for concrete analysis. Or a project package.
otherwise, if you want to see your current jar source code, or debug, you will have to build your own environment.

Menu