KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > lang > ApplicationShutdownHooks


1 /*
2  * @(#)ApplicationShutdownHooks.java 1.3 05/12/02
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7 package java.lang;
8
9 import java.util.*;
10
11 /*
12  * Class to track and run user level shutdown hooks registered through
13  * <tt>{@link Runtime#addShutdownHook Runtime.addShutdownHook}</tt>.
14  *
15  * @see java.lang.Runtime#addShutdownHook
16  * @see java.lang.Runtime#removeShutdownHook
17  */

18
19 class ApplicationShutdownHooks implements Runnable JavaDoc {
20     private static ApplicationShutdownHooks JavaDoc instance = null;
21
22     /* The set of registered hooks */
23     private static IdentityHashMap<Thread JavaDoc, Thread JavaDoc> hooks = new IdentityHashMap<Thread JavaDoc, Thread JavaDoc>();
24
25     static synchronized ApplicationShutdownHooks JavaDoc hook() {
26     if (instance == null)
27         instance = new ApplicationShutdownHooks JavaDoc();
28
29     return instance;
30     }
31
32     private void ApplicationShutdownHooks() {}
33
34     /* Add a new shutdown hook. Checks the shutdown state and the hook itself,
35      * but does not do any security checks.
36      */

37     static synchronized void add(Thread JavaDoc hook) {
38     if(hooks == null)
39         throw new IllegalStateException JavaDoc("Shutdown in progress");
40
41     if (hook.isAlive())
42         throw new IllegalArgumentException JavaDoc("Hook already running");
43
44     if (hooks.containsKey(hook))
45         throw new IllegalArgumentException JavaDoc("Hook previously registered");
46
47         hooks.put(hook, hook);
48     }
49
50     /* Remove a previously-registered hook. Like the add method, this method
51      * does not do any security checks.
52      */

53     static synchronized boolean remove(Thread JavaDoc hook) {
54     if(hooks == null)
55         throw new IllegalStateException JavaDoc("Shutdown in progress");
56
57     if (hook == null)
58         throw new NullPointerException JavaDoc();
59
60     return hooks.remove(hook) != null;
61     }
62
63     /* Iterates over all application hooks creating a new thread for each
64      * to run in. Hooks are run concurrently and this method waits for
65      * them to finish.
66      */

67     public void run() {
68     Collection<Thread JavaDoc> threads;
69     synchronized(ApplicationShutdownHooks JavaDoc.class) {
70         threads = hooks.keySet();
71         hooks = null;
72     }
73
74     for (Thread JavaDoc hook : threads) {
75         hook.start();
76     }
77     for (Thread JavaDoc hook : threads) {
78         try {
79         hook.join();
80         } catch (InterruptedException JavaDoc x) { }
81     }
82     }
83 }
84
85
Popular Tags