tags:

views:

542

answers:

4

Hi In a servlet, is destroy() called before or after finalize()?

+6  A: 

destroy() is called first. destroy() will be called by the servlet-container at the time the servlet will be shut-down. finalize() is called by the JVM before the garbage-collector claims the objects (and isn't guaranteed to be called at all).

Mnementh
Thank You for the explanation
Rahul Garg
+3  A: 

Also, finalize() may or may not be called. Don't ever rely on that happening.

mikek
A: 

finalize() method will called when object goes out of scope and eligible for garbage collection. So destroy() method definitely called before it when object doesn't got out of scope.

Silent Warrior
No, finalize() *may* be called when the object goes out of scope. It isn't guaranteed to be called at all before shutdown of the JVM.
Michael Myers
@mmyers - finalize() method at least cannot invoked before object goes out of scope, but destroy() method must be invoked before object goes out of scope. Hence destroy method always called before finalize method.
Silent Warrior
True, *if* finalize() is called, it will be called after destroy(). It just seemed misleading to say "finalize() method will be called..." instead of "finalize() method may be called..."
Michael Myers
A: 

If you want to free resources on a certain time, don't depend on external code like the servlet container or the JVM to do so. Do your resource allocation and de-allocation as explicit as possible. Nasty bugs can be the result from depending on external code to clean up after you.

Jeroen van Bergen
That's rather paranoid of you. If the servlet container doesn't call destroy() at the appropriate time, then it's crap and should be replaced with a different one. You can't go through life constantrly re-inventing the wheel, that's what application servers are there for,
skaffman
The point is that the destroy() method might be called after a considerable amount of time. That's why I said "on a certain time", meaning releasing resources explicitly from you own code is the only way to have control over WHEN the resource is released.Of course you should rely on the servlet container to do its job, but in some cases this might take too long.
Jeroen van Bergen