Re: what the benefit is by using annotation, like "@Immutable" ?
markspace <nospam@nowhere.com> wrote:
Thus, if you have your own class which follows the rules for immutablity
for some of its fields, those fields will also be treated as immutable &
safe for publication with a data race.
public class Stooges {
private final List<String> stooges; private int count;
public Stooges { stooges = new ArrayList<String>();
stooges.add("Lary"); stooges.add("Curly"); stooges.add("Moe");
}
public boolean isStooge(String name) {return stooges.contains(name);}
public int size() {
if( count == 0 ) { count = stooges.size(); } return count;
}
}
The field "stooges" is immutable and treated as such by the JVM.
I find it irritating to use the word "immutable" for a final field.
Not that it was wrong, but for fields there is already the adjective
"final" that says it all. Immutability is a "feature" of some classes'
instances, and depends on a couple of design-decisions.
If you had a non-private accessor (just a getter) for field stooges,
then your size()-implementation would be incorrect despite the final'ity
of stooges. A user could then use the reference to add another element
to the list and "final" wouldn't prevent that.
The fact that "count" is kind of lazily-immutable (*) still is
thread safe;
Huh?
As stooges is private and has not even got a getter, your class would
still be immutable even without the "final" keyword.
I don't know, how the compiler or jvm are even aware of practical
immutability, and what consequences it would draw from it, even if
it really "knew".
Hmmm, I wonder if a class can have no final fields, have at least one
mutable private field and still be immutable.
Well, yes: if it assigns all fields only in the constructor, and nowhere
else and none of the fields is other than private.