javavolatilelazy-initializationdouble-checked-lockingsonarcloud

Do I have any fault for this java:S3077?


I have a class whose fields can't help but lazily initialized.

class Some {

    public Some getPrevious() {
        {
            final Some result = previous;
            if (result != null) {
                return result;
            }
        }
        synchornized (this) {
            if (previous == null) {
                previous = computePrevious();
            }
            return previous;
        }
    }

    // all fields are final initialized in constructor
    private final String name;

    // this is a lazy initialized self-type value.
    private volatile Some previous;
}

Now sonarcloud keep complaining with java:S3077.

Use a thread-safe type; adding "volatile" is not enough to make this field thread-safe.


Solution

  • A 'thread safe type' means one which can be used by several threads without issues.

    So if Other is immutable, it is a 'thread-safe type' for the purposes of S3077.

    If it is a class which is designed to be used by several threads, e.g. a ConcurrentHashMap, then it is also a 'thread-safe type'.

    If you google S3077 you can find useful discussions which answer your question, e.g. https://community.sonarsource.com/t/java-rule-s3077-should-not-apply-to-references-to-immutable-objects/15200