This question has been asked before, and the answer is yes. However, it does require some coding.
An initial bad idea is to use a static List that stores all instances:
This causes a memory leak. Instances will never be eligible for garbage collection anymore since there will always be at least one live reference to them: the List of instances.
This issue can be solved by using a WeakHashMap. If you have not overridden hashCode() it is easy:
The WeakHashMap will never prevent a key from being garbage collected, so once the WeakHashMap is the only remaining reference the object will be eligible for garbage collection.
If you have overridden hashCode then the problem is a bit harder. You could try using a wrapper class (like WeakReference) that does not override hashCode, but the only references to those wrappers will be the WeakHashMap. That means that the wrappers are eligible for garbage collection even if the instances are not. You could solve this by giving the class a reference back; the wrapper and instance will refer to each other, and will be eligible for garbage collection when they form an island of isolation:
I've used WeakReference here since it is an existing class that still uses Object's hashCode implementation. Instead of creating an island of isolation, the WeakReferences will treat the instances a little differently; if a WeakReference is the last reference to an instance the instance is eligible for garbage collection. There are two references to each WeakReference: the instance and the WeakHashMap. The instance is now eligible for garbage collection and the WeakHashMap will not prevent garbage collection, so the WeakReferences will be eligible for garbage collection as well.
Note that none of my examples are
thread safe. There is no synchronization between adding an instance to the List / Map and returning even an unmodifiable view of it. This can cause problems. Then there is the issue of instances being published before they are fully instantiated. Read the book
Java Concurrency in Practice for more information.