I have this web application, which buffers stuff and then batch inserts said stuff into the DB. Now I want to be able to do a final batch insert whenever a Tomcat shutdown event is happening, so that I don't loose my stuff.
My app is a pretty simple Guice+Jersey API.
I've tried overriding contextDestroy of GuiceServletContextListener but it ends up in an NPE, because my injected dependencies seem to have been GC'ed at that point.
The GC can only collect resources when there are zero hard references to some instance. I think the GuiceServletContextListener is still your best bet. At this point Tomcat is trying to clean up resources before it attempts to let the GC reclaim the ClassLoader that your app is running in. Everything you need should still be available as long as you have a hard reference.
When you create your Injector, hold on to a reference of a Provider that returns a class that does your cleanup. When contextDestroyed is called, get an instance of the cleanup class from the provider and run the logic.
Setups
Injector, keep an instance of the provider that returns the cleanup class in your GuiceServletContextListener (Don't keep an instance of the Injector. It contains the entire dependency tree).contextDestroyed method is called, use the provider to get an instance of the cleanup class and run the logic.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With