I have been trying to design a system in Java where I can track resources like Images and Audio files loaded from disk and unloading them when there are no references to it.
In C++ I could override the delete operator so I could decrement the reference.
But Java works with automatic garbage collection which destroys an object when it has no references.
Because I keep track of all the resources in my resourcemanager, the reference to the object will never be null, thus the resources will never be unloaded if they are not needed.
Is there a way to keep track of the objects while at the same time deleting them while they have no references from entities?
I have heard a deconstructor is not safe so that’s also not an option
Use WeakRefence in your resourcemanager, e.g. a WeakHashMap.
You can find a good explanation of WeakReferences (and other references e.g. Softreference) here: http://weblogs.java.net/blog/2006/05/04/understanding-weak-references
Simple said:
A weak reference is a reference that does not to force the object to stay in memory. If there is no strong reference to the object, but you still have the weak reference in your resourcemanager, the object is still eliglible for garbage collection and can be deleted by the garbage collector.