A problem with the object pool optimisation is that it can cause a memory leak. Once a Point
is created and added to pool
it can never be released, even if there are no references to the point in the rest of the application. The fact that pool
references the point means that the point cannot be garbage-collected.
This problem has the potential to cause exhaustion of heap memory. Demonstrate this by writing a simple program that uses makePoint
to create, but not keep track of, a vast number of distinct Point
objects. If you create a large enough number of points, you should find that your program quits with an "out of memory" error.
You can solve this issue through the use of Java's WeakReference
and WeakHashMap
classes.
Read about these classes in the Java documentation:
-
https://docs.oracle.com/javase/9/docs/api/java/lang/ref/WeakReference.html
-
https://docs.oracle.com/javase/9/docs/api/java/util/WeakHashMap.html
Use these classes to change your implementation of Point
pooling so that a memory leak cannot occur. Write a program to demonstrate that this is working: your program should create, but not keep track of a large number of objects. After this, your program should print the size of pool
(to do the latter, you should add a public static method to Point
to retrieve this size).
Hint: The apparent type of pool
should be changed to:
Map<Point, WeakReference<Point>>
while the actual type of pool
should become:
WeakHashMap<Point, WeakReference<Point>>