简体   繁体   中英

Is null when new ArrayList

I had a error when watching online product, code is like this, but an NullPointedException bother me, this error only appear once, and I can not reappear it. I can not understand why ArrayList is [null, 1] :

public void test4() {
    class PlayerTask {
        List<Integer> targetValueList;

        List<Integer> getTargetValueList() {
            if (null == targetValueList) {
                init();
            }
            return targetValueList;
        }

        private void init() {
            targetValueList = new ArrayList<>();
            targetValueList.add(Integer.parseInt("1"));
        }
    }
    PlayerTask task = new PlayerTask();

    //some code1
    new Thread(() -> {
        task.getTargetValueList().get(0); // NullPointException ,real array is [null, 1]
    }).start();

    //some code2
    new Thread(() -> {
        task.getTargetValueList().size();
    }).start();

    // some code ...
    new Thread(() -> {
        task.getTargetValueList().get(0);
    }).start();

    // ....
    ///task.getTargetValueList().get(..)...
}

Your code is multi-threaded yet you are not guarding against possible race condition when creating and accessing new ArrayList<>() . The quickest way to solve this problem would be to synchronize getTargetValueList() method:

synchronized List<Integer> getTargetValueList() {
    if (null == targetValueList) {
        init();
    }
    return targetValueList;
}

Take a moment to read Safe Publication and Safe Initialization in Java . It gives great insight how this approach can be improved and why certain patterns like Double-Checked Locking are a bad idea.

If you want to learn more about concurrency the book Java Concurrency in Practice is a good starting point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM