Java Reference
In-Depth Information
4.4.2. Creating immutable objects
With the rise of multi-core machines, programs that handle concurrency well are becoming
more and more important. One mechanism for handling operations in a thread-safe manner
is to use immutable objects as much as possible whenever shared information is required.
Unlike C++, Java has no built-in way to make it impossible to modify an object. There's
no “const” keyword in Java, and applying the combination of
static
and
final
to a
reference only makes the reference a constant, not the object it references. The only way to
make an object immutable in Java is to remove all ways to change it.
This turns out to be a lot harder than it sounds. Taking out all setter methods is a good first
step, but there are other requirements. Making a class support immutability requires that
• All mutable methods (setters) must be removed.
• The class should be marked
final
.
• Any contained fields should be
private
and
final
.
• Mutable components like arrays should defensively be copied on the way in
(through constructors) and the way out (through getters).
•
equals
,
hashCode
, and
toString
should all be implemented through fields.
That sounds like work. Fortunately Groovy has an @
Immutable
AST transformation,
which does everything for you (see
figure 4.6
)
.