1) The JVM decides when to run garbage collection. You can request that it happens and the JVM may run and it may not run when but you cannot count on it.
2) However even if it does run and your finalize method does get ran it will only get run once.
3) If you finalize method does run but you haven't cleaned up your program correctly the next time garbage collection runs your finalize method WILL NOT get run.
In the end, you have no control over the fact that your finalize method runs. So it's best to either not use it, however if you do then don't put anything it that method that you expect to run all the time. A bad programmer may put something like this in their finalize method and they may not experience any side effects most of the time:
I want to reiterate that the above code is bad and used for example purposes only.
“The strongest of all warriors are these two — Time and Patience.” ― Leo Tolstoy, War and Peace
Pete Letkeman wrote:I want to reiterate that the above code is bad and used for example purposes only.
If you post a code snippet (even if it demonstrates bad code), you should make sure that the code compiles successfully (unless you are of course asking a question about a compiler error).
PS. Always use code tags when posting code to the forums. Unformatted or unindented code is extremely hard to read and many people that might be able to help you will just move along to posts that are easier to read. Please click this link ⇒ UseCodeTags ⇐ for more information. Properly indented and formatted code greatly increases the probability that your question will get quicker, better answers. I already added the code tags for you. See how much easier the code is to read?