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.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3e33a-2c3ea.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3e33a-2c3ea.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?