Jin Kwon
Jin Kwon

Reputation: 21997

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.

Upvotes: 1

Views: 1871

Answers (1)

tgdavies
tgdavies

Reputation: 11464

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

Upvotes: 1

Related Questions