Search code examples
javathread-safetyguavascheduler

Guava AbstractScheduledService on server environment


What is the preferred way of shutting down an AbstractScheduledService running in server environment (e.g. Tomcat) when the application server is shutting down? Do I have to explicitly register a server listener for this, or is there a way to specify the service threads as daemons?


Solution

  • The standard way to manage Services (including/particularly in a server) is using ServiceManager. Add all the services to a ServiceManager and then startAsync() the manager on startup and stopAsync() on shutdown. You would need a server listener for this.

    It is possible to specify the service threads as daemons by overriding the executor() method of the AbstractScheduledService and returning an executor that uses a ThreadFactory that produces daemon threads, but note that if you do that, the executor won't automatically be shutdown if/when the AbstractScheduledService itself is stopped (though you can add a listener to the service that will do this just like the default executor() implementation does).

    That said, I'd recommend ServiceManager plus a server listener. That approach should ensure an orderly shutdown of your services.