Solution to 290b: Memory leaks in Java
See code at solutions/code/tutorialquestions/question290b
See standardreferences.Demo for a program that causes an "out of memory" error.
The Point class in the weakreferences package shows how Java's
WeakReference and WeakHashMap classes can be used to avoid the
memory leak problem. The pool map is changed so that it maps Point
objects to WeakReference<Point> objects. Furthermore, point is
instantiated to be a WeakHashMap rather than a HashMap.
In makePoint, the line:
pool.put(p, p);
is changed to:
pool.put(p, new WeakReference<Point>(p));
---the reference p specified as the value part of the map entry is
wrapped in a WeakReference.
The result
of this is that if a Point object is only active because it is a member of
pool, it is allowed to be garbage-collected.
Class weakreferences.Demo demonstrates that this solution works by creating
a vast number of distinct Point objects, but not keeping a reference to any
of them. Because of the use of weak references in the implementation of object pooling,
these objects will eventually be garbage-collected, so memory is not exhausted.