Java Reference
In-Depth Information
possible states of complex objects. Reasoning about the state of immutable objects, on the
other hand, is trivial.
Immutable objects are also
safer
. Passing a mutable object to untrusted code, or otherwise
publishing it where untrusted code could find it, is dangerous—the untrusted code might
modify its state, or, worse, retain a reference to it and modify its state later from another
thread. On the other hand, immutable objects cannot be subverted in this manner by malicious
or buggy code, so they are safe to share and publish freely without the need to make defensive
copies [EJ Item 24].
Neither the Java Language Specification nor the Java Memory Model formally defines im-
mutability, but immutability is
not
equivalent to simply declaring all fields of an object
fi-
nal
. An object whose fields are all final may still be mutable, since final fields can hold
references to mutable objects.
An object is
immutable
if:
•
Its state cannot be modifled after construction;
•
•
It is
properly constructed
(the
this
reference does not escape during construction).
Immutable objects can still use mutable objects internally to manage their state, as illustrated
design of
ThreeStooges
makes it impossible to modify that
Set
after construction. The
stooges
reference is
final
, so all object state is reached through a
final
field. The last
requirement, proper construction, is easily met since the constructor does nothing that would
cause the
this
reference to become accessible to code other than the constructor and its
caller.
Listing 3.11. Immutable Class Built Out of Mutable Underlying Objects.