KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > util > CommonShutDownHook


1 /**
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package com.tc.util;
5
6 import java.util.ArrayList JavaDoc;
7 import java.util.List JavaDoc;
8
9 public class CommonShutDownHook implements Runnable JavaDoc {
10   private static final List JavaDoc runnables = new ArrayList JavaDoc();
11   private static Thread JavaDoc hooker; // ;-)
12

13   public static void addShutdownHook(Runnable JavaDoc r) {
14     if (r == null) { throw new NullPointerException JavaDoc("Shutdown hook cannot be null"); }
15     synchronized (runnables) {
16       runnables.add(r);
17
18       if (hooker == null) {
19         hooker = new Thread JavaDoc(new CommonShutDownHook());
20         hooker.setName("CommonShutDownHook");
21         hooker.setDaemon(true);
22         Runtime.getRuntime().addShutdownHook(hooker);
23       }
24     }
25   }
26
27   public void run() {
28     // Use a copy of the hooks for good measure (to avoid a possible ConcurrentModificationException here)
29
final Runnable JavaDoc[] hooks;
30     synchronized (runnables) {
31       hooks = (Runnable JavaDoc[]) runnables.toArray(new Runnable JavaDoc[runnables.size()]);
32     }
33
34     for (int i = 0; i < hooks.length; i++) {
35       Runnable JavaDoc r = hooks[i];
36       Thread.currentThread().setName("CommonShutDownHook - " + r);
37
38       try {
39         r.run();
40       } catch (Throwable JavaDoc t) {
41         t.printStackTrace();
42       }
43     }
44   }
45 }
46
Popular Tags