I understand that finalize runs asychronously so you can therefore not determine when it will run. My question is, can you be guarnateed that the finalize method will be run at all? I have read both that it will be run eventually and that it may never be run. Which is correct? Thanks, Rob
An object's finalizer is guaranteed to run before the storeage allocated to an object is reused. Finalizers are not normally run when System.exit() is called. For more information, see the API documentation on Runtime.runFinalizersOnExit(). You will see that, at least for JDK 1.3.1, setting finalizers to run on exit() is not recommended.
The finalize method of an object is guaranteed to be called when the garbage collector is going to clean this object. So it's the garbage collector that makes the call to Finalize. If the garbage doesn't run, there won't be any call to finalize(). I hope It helps
By constantly trying one ends up succeeding. Thus: the more one fails the more one has a chance to succeed.
posted 18 years ago
Originally posted by Younes Essouabni: The finalize method of an object is guaranteed to be called when the garbage collector is going to clean this object. So it's the garbage collector that makes the call to Finalize. If the garbage doesn't run, there won't be any call to finalize(). I hope It helps
So let me ask, is there any way to guarantee that garbage collection for every object will run? Thanks, Rob
posted 18 years ago
If I were going to try to force as much finalization as possible, I would: 1. After taking the warnings in the API documentation for Runtime.runFinalizationOnExit(), set runFinalizationOnExit(true) 2. Remove all references to objects of interest, run try System.gc() a time or two to clean up what it can, and then try System.runFinalization(). However, before relying on finalization, find a copy of Effective Java, by Joshua Bloch, and study Item 6, "Avoid finalizers". He explains issues in using finalization, how to avoid it, when to use it, and how to use it effectively when necessary, all in about four pages As for my suggestion above, consider this quote from Bloch:
Don't be seduced by the methods Sytem.gc and System.runFanalization. They may increase the odds of finalizers getting executed, but they don't guarantee it. The only methods that claim to guarantee finalization are System.runFinalizersOnExit and its evil twin, Runtime.runFinalizersOnExit. There methods are fatally flawed and have been deprecated.
[ May 27, 2002: Message edited by: John Dale ]
It would give a normal human mental abilities to rival mine. To think it is just a tiny ad: