Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@PreDestroy not called on session-scoped Spring bean on tomcat shutdown

Using Spring 3.0.5 GA

Have a Session-scoped bean with @PreDestroy method. Just noticed that if owning HttpSession times out (ie exceeds Servlet Container's session-timeout value) then @PreDestroy call back is issued. However, if I simply shutdown the app server, @PreDestroy is NOT called. Is that by design or is a bug? If latter, any suggestions for a work-around?

FWIW, @PreDestroy on singleton beans gets called in both cases.

thanks, -nikita

PS. There is a possibly-related Spring bug - SPR-7359

like image 787
Nikita Avatar asked Mar 01 '11 20:03

Nikita


2 Answers

Interesting. Session-scoped beans have their @Predestroy invoked when the session-close event occurs. If the container never sends that event, then Spring won't be informed. I'm not sure if this constitutes a bug or not, and if so, whetyer it's a bug in Spring or Tomcat. The latter seems more likely, but I don't know if a Servlet container is obliged to do this.

If this is a show-stopper for you, you might want to consider having the scoped bean register itself with a "registrar" singleton during its @PostConstruct, and deregister itself on @PreDestroy. If the registrar is shutdown, it can propagate that event to any remaining session-scoped beans still registered with it.

Not ideal, but a pragmatic solution.

like image 66
skaffman Avatar answered Sep 28 '22 20:09

skaffman


I would guess this is by design.

Tomcat, for instance, stores its sessions in SESSIONS.ser, by default for each deployed application. If you shut down Tomcat and restart it, it re-reads SESSIONS.ser. So, I would guess that as far as Spring is concerned, shutting down the container doesn't necessarily mean terminating the session - so that means @PreDestroy methods aren't called on session-scoped beans.

like image 22
BobG Avatar answered Sep 28 '22 18:09

BobG