---
title: "Java cleanup code"
author: "willpower"
date: "2007-04-03T12:20:26Z"
tags: []
slug: "java-cleanup-code"
draft: false
lastmod: "2007-04-03T12:20:26Z"
id: 67578
url: "https://willpower.iteye.com/blog/67578"
---

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 代码

01. /\**
02. * A class to track the list of DFS clients, so that they can be closed
03. * on exit.
04. * @author Owen O'Malley
05. \*/
06. private static class ClientFinalizer extends Thread {
07. private List clients = new ArrayList();
08. public synchronized void addClient(DFSClient client) {
09. clients.add(client);
10. }
11. public synchronized void run() {
12. Iterator itr = clients.iterator();
13. while (itr.hasNext()) {
14. DFSClient client = (DFSClient) itr.next();
15. if (client.running) {
16. try {
17. client.close();
18. } catch (IOException ie) {
19. System.err.println("Error closing client");
20. ie.printStackTrace();
21. }
22. }
23. }
24. }
25. }
26. // add a cleanup thread
27. private static ClientFinalizer clientFinalizer = new ClientFinalizer();
28. static {
29. **Runtime.getRuntime().addShutdownHook(clientFinalizer);**
30. }

Elegant and useful!!!