Java Transient Keyword and null

I am using Intellij IDEA, and the following code generates a warning: " Expression testObj might evaluate to null but is returned by the method declared as @NotNull (at line 16)"

package com.dlp;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public class TestCase {
    @Nullable
    private transient Object testObj = null;

    @Nonnull
    public Object getTestObj() {
        if(testObj == null) {
            testObj = new Object();
        }

        return testObj; //Line 16
    }
}

This only happens if I mark testObj as transient. Removing a keyword clears the warning. Is there some kind of interaction between short-term and invalid that I don't get, or is it just a mistake in IDEA?

+4
source share
1 answer

Fault tolerance is very complex in the compiler. Yes, you check for null, but there is a problem that your code can be used in a multi-threaded context. Consider this scenario:

This block is executed:

    if(testObj == null) {
        testObj = new Object();
    }

, testObj null. null testObj.

, , :

public Object getTestObj() {
    Object tmpObj = testObj
    if(tmpObj == null) {
        tmpObj = new Object();
        testObj = tmpObj;
    }

    return tmpObj;
}

, .

, , , null.

, , IntelliJ. , nullability . , .

0

All Articles