I'm using OpenGL in Java and I have to delete external resources (like vbos). The recommended way is to have a Disposable
interface. However doing that would require me to have nearly every class dealing with resources implement this interface. And I've tried that but it's often not clear to me which object should be responsible for calling the dispose()
method. That's why I programmed something like this:
public abstract class Destroyable {
private static final ArrayList<Runnable> cleanupTasks = new ArrayList<Runnable>();
public static void cleanup() {
synchronized (cleanupTasks) {
for (Runnable cleanupTask : cleanupTasks) {
cleanupTask.run();
}
}
}
protected abstract void destroy();
@Override
protected void finalize() throws Throwable {
try {
synchronized (cleanupTasks) {
// Let's do cleanup in the main thread as the garbage collector runs in another thread
cleanupTasks.add(new Runnable() {
public void run() {
destroy();
}
});
}
} finally {
super.finalize();
}
}
}
As the garbage collector won't run most of the time I'm calling Destroyable.cleanup()
together with System.gc()
every five seconds.
It's not that bad if some of the resources aren't destroyed at the end (like static ones) because I'm deleting the context at the end (which destroys the other resources as well).
Is this a good idea or is there a better way of doing this?