01: /**
02: * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
03: */package com.tc.util;
04:
05: import java.util.ArrayList;
06: import java.util.List;
07:
08: public class CommonShutDownHook implements Runnable {
09: private static final List runnables = new ArrayList();
10: private static Thread hooker; // ;-)
11:
12: public static void addShutdownHook(Runnable r) {
13: if (r == null) {
14: throw new NullPointerException(
15: "Shutdown hook cannot be null");
16: }
17: synchronized (runnables) {
18: runnables.add(r);
19:
20: if (hooker == null) {
21: hooker = new Thread(new CommonShutDownHook());
22: hooker.setName("CommonShutDownHook");
23: hooker.setDaemon(true);
24: Runtime.getRuntime().addShutdownHook(hooker);
25: }
26: }
27: }
28:
29: public void run() {
30: // Use a copy of the hooks for good measure (to avoid a possible ConcurrentModificationException here)
31: final Runnable[] hooks;
32: synchronized (runnables) {
33: hooks = (Runnable[]) runnables
34: .toArray(new Runnable[runnables.size()]);
35: }
36:
37: for (int i = 0; i < hooks.length; i++) {
38: Runnable r = hooks[i];
39: Thread.currentThread().setName("CommonShutDownHook - " + r);
40:
41: try {
42: r.run();
43: } catch (Throwable t) {
44: t.printStackTrace();
45: }
46: }
47: }
48: }
|