ca.wumbo.doommanager.util.ShutdownHook.java Source code

Java tutorial

Introduction

Here is the source code for ca.wumbo.doommanager.util.ShutdownHook.java

Source

/*
 * DoomManager
 * Copyright (C) 2014  Chris K
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package ca.wumbo.doommanager.util;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configurator;
import org.springframework.context.ConfigurableApplicationContext;

/**
 * A custom shutdown hook is needed because Spring needs to be shutdown before
 * Log4J2. Since Log4j uses it's own shutdown hook, this can run at any time
 * and not guarantee proper logging on shutdown. The solution then was to use
 * my own shutdown hook which will terminate Spring, followed by Log4j at the
 * end.
 * 
 * TODO - This needs better/safer integration with the application and Spring.
 */
class ShutdownHook extends Thread {

    /**
     * The logger for this class.
     */
    private static Logger log = LogManager.getLogger(ShutdownHook.class);

    /**
     * The context for Spring.
     */
    private ConfigurableApplicationContext ctx;

    /**
     * Creates a shutdown hook thread.
     * 
     * @param ctx
     *       The Spring context to shutdown on exit.
     * 
     * @throws NullPointerException
     *       If the argument is null.
     */
    public ShutdownHook(ConfigurableApplicationContext ctx) {
        if (ctx == null)
            throw new NullPointerException("Passed a null Spring application context to a shutdown hook.");
        this.ctx = ctx;
        log.debug("Registered Spring context with a Shutdown hook thread.");
    }

    @Override
    public void run() {
        log.debug("Shutting down Spring...");
        ctx.close();

        log.debug("Spring shutdown successful, shutting down logging server.");
        Configurator.shutdown((LoggerContext) LogManager.getContext());
    }
}