Search in sources :

Example 1 with StoppableService

use of com.peterphi.std.guice.common.shutdown.iface.StoppableService in project stdlib by petergeneric.

the class ShutdownManagerImpl method shutdown.

@Override
public synchronized void shutdown() {
    if (stopped) {
        log.warn("Ignoring duplicate shutdown request");
    }
    // Allow services to shut down cleanly
    if (!services.isEmpty()) {
        // count the number of services that failed to shutdown
        int failures = 0;
        log.info("Shutting down " + services.size() + " service(s)");
        // First, notify all services about the impending shutdown
        // We can't iterate across the stack in the right order without doing so destructively, so we create a copy as a list
        // And then reverse it to mimic the stack being iterated across using the right order
        {
            final List<StoppableService> toNotify = new ArrayList<>(services);
            for (StoppableService service : toNotify) {
                try {
                    service.preShutdown();
                } catch (Throwable t) {
                    failures++;
                    log.warn("Pre-Shutdown failed for " + service + ":" + t.getMessage(), t);
                }
            }
        }
        // Now, shutdown all the services, unregistering them from the service stack at the same time
        while (!services.empty()) {
            final StoppableService service = services.pop();
            try {
                log.debug("Requesting shutdown of " + service);
                service.shutdown();
            } catch (Throwable t) {
                failures++;
                log.warn("Shutdown failed for " + service + ": " + t.getMessage(), t);
            }
        }
        if (failures == 0) {
            log.info("Shutdown complete");
        } else {
            log.warn("Shutdown completed, " + failures + " service(s) threw an exception during shutdown");
        }
        stopped = true;
        services.clear();
    }
}
Also used : List(java.util.List) ArrayList(java.util.ArrayList) StoppableService(com.peterphi.std.guice.common.shutdown.iface.StoppableService)

Aggregations

StoppableService (com.peterphi.std.guice.common.shutdown.iface.StoppableService)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1