Re: Usefulness of "final" (Was: Re: Inserting In a List)
markspace wrote:
Eric Sosman wrote:
I'm with Arne. The cited section uses the word "immutable"
and "immutability" without defining either. All it says is that
"final" can be an aid to implementing immutable objects -- but it
never says what "immutable" is.
Well, it does. Section 17.5 has several subsections, and it's defined
in section 17.5.1. I feel one really should read all of 17.5 to
understand final fields however.
Section 17.5.1 never mentions the word "immutable" at all.
http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.5.1
Section 17.5, however, does define "thread-safe immutable":
" A thread-safe immutable object is seen as immutable by all threads, even if a data race is used to pass references to the immutable object between threads."
The word "immutable" is apparently to be understood in its common computer-science meaning.
[snip]
I think immutable is defined in section 17.5.1, with their "hb(w, f),
hb(f, a), mc(a, r1), and dereferences(r1, r2)" stuff. That section is
as I say clear as mud, and I'm relying on Brian Goetz in JCIP to
interpret that mess correctly for me.
That section does not address immutability, but finality.
It says that the value of a reference will not be seen to change if the conditions pertain,
but says nothing about the state of the object referenced.
Thought experiment: Using the JLS' definition of immutability,
There isn't one.
support or refute "java.lang.String is mutable, because it computes
its hashCode() lazily and caches it in a non-final field, thereby
changing the String object's state at the first hashCode() call."
Clearly they use "immutable" to refer to observable ("perceived") state.
Any two calls to a fully-constructed 'String' instance's 'hashCode()' will be perceived
to have the same value, and thus is immutable to conventional observation.
But all threads will see the String's internal char[] to have the same
values, because it's safely published through a final field. So all
threads will calculate the same hash code. This isn't really "thread
safe," except that it is because being idempotent counts. Threads can
Yes, it is really thread safe, assuming you wait for the ctor to complete.
never seen any value for the internally stored hash code except 0 or the
correctly computed value.
And if you follow the rules of thread-safe immutability, and I don't know how you would
dodge them for 'String', threads will never see 0.
--
Lew