
de.weltraumschaf.commons.ShutDownHook Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of commons Show documentation
Show all versions of commons Show documentation
Common Utility Classes for Java.
/*
* LICENSE
*
* "THE BEER-WARE LICENSE" (Revision 43):
* "Sven Strittmatter" wrote this file.
* As long as you retain this notice you can do whatever you want with
* this stuff. If we meet some day, and you think this stuff is worth it,
* you can buy me a non alcohol-free beer in return.
*
* Copyright (C) 2012 "Sven Strittmatter"
*/
package de.weltraumschaf.commons;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Holds {@link Runnable callbacks} to execute them in any order.
*
* Example:
*
* ShutDownHook hook = new ShutDownHook();
* hook.register(new Runnable() {
*
* @Override
* public void run() {
* // Your shutdown code.
* }
*
* });
*
* @author Sven Strittmatter
*/
public class ShutDownHook extends Thread {
/**
* Default logger for this class.
*/
private static final Logger DEFAULT_LOGGER = Logger.getLogger(ShutDownHook.class.getName());
/**
* Set of callbacks.
*/
private final Set callbacks = new HashSet();
/**
* Logger instance.
*/
private final Logger logger;
/**
* Initializes {@link #logger} with {@link #DEFAULT_LOGGER}.
*/
public ShutDownHook() {
this(DEFAULT_LOGGER);
}
/**
* Designated constructor.
*
* @param logger Logger to use by this class.
*/
public ShutDownHook(final Logger logger) {
super();
this.logger = logger;
}
/**
* Iterates over all {@link #callbacks} and run them.
*/
@Override
public void run() {
final Iterator iterator = callbacks.iterator();
while (iterator.hasNext()) {
try {
iterator.next().run();
} catch (Exception ex) {
logger.log(Level.SEVERE, "Exception thrown by running a callback!", ex);
}
}
}
/**
* Registers a callback.
*
* @param callback Runnable object.
* @return Return itself for method chaining.
*/
public ShutDownHook register(final Runnable callback) {
callbacks.add(callback);
return this;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy