I understand that spring's lifecycle callback init-method
is useful when you need to do initializations based on the dependencies injected by the IoC framework that can't be done in the regular contructor
method. But what is the advantage of doing clean ups in the lifecyle callback destroy-method
over regular finalize
method?

- 10,095
- 5
- 27
- 45
-
3finalize in not "regular", and you shouldn't rely on it - it's up to the garbage collector to call it or not, and at the time it chooses - it's bad practice to use it – Guillaume Nov 16 '11 at 16:39
-
@Guillaume: By 'regular' I meant something part of java itself and not spring-specific. But thanks for you reply. – Raihan Nov 16 '11 at 16:42
-
And by "not regular" I meant this is to be used by the JVM, not by users :) Unless you really know what you're doing. And in this case, don't forget to call super.finalize() in a finally clause. – Guillaume Nov 16 '11 at 16:46
-
@Guillaume: I admit `destroy` is NOT regular :-) – Raihan Nov 16 '11 at 16:48
4 Answers
finalize
is called by the garbage collector and thus is not guaranteed to be invoked.
Springs destroy-method
or @PreDestroy
annotation is called by the container when the spring container is destroying beans, e.g., on application is shutdown, allowing you to deregister services, terminate threads or perform various cleanup code.

- 1
- 1

- 47,929
- 21
- 130
- 148
-
Can't you place the same cleanup code in `finalize()`? Is there any spring framework specific cleanups that must go in the `destroy-method`? – Raihan Nov 16 '11 at 16:40
-
Yes you can place the same code in `finalize`, but not always guarantee that it will be run, or run in a timely fashion – Johan Sjöberg Nov 16 '11 at 16:42
The destroy-method
has more to do with managing bean destruction when the bean's container is destroyed. finalize()
is for the JVM, really, and isn't directly tied to Spring's lifecycle management.
IMO Spring-managed beans should prefer destroy-method
both to keep things communicative (it's more obvious, because it's stated explicitly) and to ensure that destruction happens under more-controlled circumstances.

- 158,873
- 26
- 254
- 302
Others have provided good answers, but I thought I'd add a piece of explanation on the finalize()
method.
As a good practice, you should not put application critical code in the finalize()
method, as there's no guarantee when it will be called (or if it will be called). You can put some last-ditch effort code in there to make sure resources used by a class are freed (files, or communication ports for instance), but you should never rely on this method to do any required cleanup.
Whenever you have a mechanism in place to destroy objects (such as the destroy callback in the Spring framework), you should definitely use it to free resources.

- 7,965
- 4
- 37
- 52