Java shutdown hook guarantee that clean-up code is always run, regardless of how the user terminates the application.
Here is an example from Hadoop:
java 代码
- /**
- * A class to track the list of DFS clients, so that they can be closed
- * on exit.
- * @author Owen O'Malley
- */
- private static class ClientFinalizer extends Thread {
- private List clients = new ArrayList();
- public synchronized void addClient(DFSClient client) {
- clients.add(client);
- }
- public synchronized void run() {
- Iterator itr = clients.iterator();
- while (itr.hasNext()) {
- DFSClient client = (DFSClient) itr.next();
- if (client.running) {
- try {
- client.close();
- } catch (IOException ie) {
- System.err.println("Error closing client");
- ie.printStackTrace();
- }
- }
- }
- }
- }
- // add a cleanup thread
- private static ClientFinalizer clientFinalizer = new ClientFinalizer();
- static {
- Runtime.getRuntime().addShutdownHook(clientFinalizer);
- }
Elegant and useful!!!