ITeye博客

Java cleanup code

willpower · 2007-04-03 12:20 · Study 学习 · Markdown

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

  1. /**
  2. * A class to track the list of DFS clients, so that they can be closed
  3. * on exit.
  4. * @author Owen O'Malley
  5. */
  6. private static class ClientFinalizer extends Thread {
  7. private List clients = new ArrayList();
  8. public synchronized void addClient(DFSClient client) {
  9. 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!!!

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。