Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a final DB push when a Tomcat shutdown occurs?

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.

like image 774
deiga Avatar asked Nov 04 '25 08:11

deiga


1 Answers

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

  1. Write a cleanup class, containing all of the needed dependencies.
  2. Bind this cleanup class to guice.
  3. When you create the 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).
  4. When the contextDestroyed method is called, use the provider to get an instance of the cleanup class and run the logic.
like image 192
Isaiah van der Elst Avatar answered Nov 06 '25 23:11

Isaiah van der Elst



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!