I would like to suggest a modification to rule squid:S3077 (Non-primitive fields should not be “volatile”)
The rationale for the rule is that the
volatile keyword is not sufficient to guarantee that changes to fields of object referents are seen by other threads. However, if the referent is immutable, there may be no changes to fields.
Consequently, a field that holds a volatile reference to a non-primitive immutable type should not trigger the rule.
private volatile MyImmutableType foo; // Compliant -- reference may change, // but object referred to may not.
Enum constants should be considered immutable for this purpose. (Although it is technically possible to implement mutable enum constants, I would argue that using mutable enum constants is a design flaw of its own.)
private volatile MyEnumType status; // Compliant -- enum constant // should be immutable.
See also CERT, CON50-J.:
“[…] when the referent is immutable, declaring the reference volatile suffices to guarantee safe publication of the members of the referent. […] Use of the
volatilekeyword can only guarantee safe publication of primitive fields, object references, or fields of immutable object referents.”