So, I recently discovered the finalize method in Java (not sure why I missed it before, but there it is). This seems like it could be the answer to a lot of the issues I’m working with, but I wanted to get a bit more information first.
Online, I found this diagram illustrating the process of garbage collection and finalize:

A couple of questions:
- This takes place in a separate thread, correct?
- What happens if I instantiate a new object during finalize? Is that allowed?
- What happens if I call on a static method from finalize?
- What happens if I establish a new reference to the object from within finalize?
I suppose I should explain why I’m interested. I work with LWJGL a lot, and it seems that if I could use finalize to cause Java objects to automatically clean up OpenGL resources, then I could do some really nice things in terms of an API.
I don’t think there are any guarantees about what thread will be used. New objects may be instantiated and static methods may be called. Establishing a new reference to your object will prevent it from being garbage collected, but the
finalizemethod will not be called again–you don’t want to do this.Cleaning up resources is precisely what the
finalizemethod is for, so you should be good there. A couple of warnings, though:The method is not guaranteed to be called. If you have tied up resources that will not automatically be freed when your program stops do not depend on
finalize.When the method is called is not guaranteed. With memory tight, this will be sooner. With lots of free memory, it will be later if at all. This may suit you fine: with lots of memory you may not be all that concerned about freeing up the resources. (Though hanging on to them may interfere with other software running at the same time, in which case you would be concerned.)
My ususal solution is to have some kind of dispose method that does the clean up. I call it explicitly at some point if I can, and as soon as I can. Then I add a finalize method that just calls the dispose method. (Note that the dispose method must behave well when when called more than once! Indeed, with this kind of programming I might call dispose several times outside
finalize, not being sure if previous calls were made successfully and yet wanting it to be called effectively as soon as possible.) Now, ideally, my resources are freed as soon as I no longer need them. However, if I lose track of the object with the resources, thefinalizemethod will bail me out when memory runs short and I need the help.