1

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.

  • Is there anything wrong with the code?
  • Can(Should) I ignore it?
  • What about using AtomicReference? Isn't it an overkill?
Jin Kwon
  • 20,295
  • 14
  • 115
  • 184
  • Is `Other` mutable? If so, as metioned in the rule description, https://rules.sonarsource.com/java/RSPEC-3077, other threads may fail to see the updates in the shared instances. So looks like a valid issue. – Prasanna Dec 27 '20 at 08:19

1 Answers1

1

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

tgdavies
  • 10,307
  • 4
  • 35
  • 40