Solution to 1ae9: Reusing immutable value objects
See code at solutions/code/tutorialquestions/question1ae9
I have implemented makePoint
as follows:
public static Point makePoint(int coordX, int coordY, int coordZ) {
Point p = new Point(coordX, coordY, coordZ);
if (pool.get(p) != null) {
return pool.get(p);
// p will now be garbage collected
}
pool.put(p, p);
return p;
}
The first thing this method does is calls the constructor of Point
to make a new point. So the approach does not prevent
lots of identical points from being created. However, it does avoid lots of identical points being stored forever.
The test: if(pool.get(p) != null)
checks whether pool
contains an entry of the form (first, second)
such that p.equals(first)
holds.
If this is the case, the method returns second
. As a result, there are no
references to the point that was referred to by p
, and eventually (though, as confirmed in question b4a5, we do not know when)
the point will be garbage-collected.
Otherwise, the statement pool.put(p, p)
causes the entry (p, p)
to be inserted into the pool. This means that
in future, if we call have a point t
with t.equals(p)
, the test pool.get(t) != null
will hold.
As a result, we will never permanently create another point that is identical to p
.
See class objectpool.Demo
for a demonstration that this solution really works.