Java Reference
In-Depth Information
The best example of this is the Boolean class. In any Java application, there need ever be
only two instances of the Boolean class: one for true, and one for false. Unfortunately, the
Boolean class is badly designed. Because it has a public constructor, applications can create
as many of these objects as they like, even though they are all exactly the same as one of the
two canonical Boolean objects. A better design would have been for the Boolean class to
have only a private constructor, and static methods to return either Boolean.TRUE or
Boolean.FALSE based on their parameter. If such a model can be followed for your own im-
mutable classes, you can prevent them from contributing to the heap usage of your applica-
tion. (Hopefully it is obvious that you should never create a Boolean object; you should just
use Boolean.TRUE or Boolean.FALSE as necessary.)
These singular representations of immutable objects are known as the canonical version of
the object.
Creating canonical objects
Even if the universe of objects for a particular class is practically limitless, using canonical
values can often save memory. The JDK provides a facility to do this for the most-common
immutable object: strings can call the intern() method to find a canonical version of the
string. More details of string interning are examined in the next section, but for now we'll
look at how to accomplish the same thing for custom classes.
To canonicalize an object, create a map that stores the canonical version of the object. In or-
der to prevent a memory leak, make sure that the objects in the map are weakly referenced.
The skeleton of such a class looks like this:
public
public class
ImmutableObject {
WeakHashMap < ImmutableObject , ImmutableObject > map = new
class ImmutableObject
new WeakHashMap ();
public
public ImmutableObject canonicalVersion ( ImmutableObject io ) {
synchronized
synchronized ( map ) {
ImmutableObject canonicalVersion = map . get ( io );
iif ( canonicalVersion == null
null ) {
map . put ( io , io );
canonicalVersion = io ;
}
return
return canonicalVersion ;
}
}
}
Search WWH ::




Custom Search