1 7 package java.lang; 8 9 import java.util.*; 10 11 18 19 class ApplicationShutdownHooks implements Runnable { 20 private static ApplicationShutdownHooks instance = null; 21 22 23 private static IdentityHashMap<Thread , Thread > hooks = new IdentityHashMap<Thread , Thread >(); 24 25 static synchronized ApplicationShutdownHooks hook() { 26 if (instance == null) 27 instance = new ApplicationShutdownHooks (); 28 29 return instance; 30 } 31 32 private void ApplicationShutdownHooks() {} 33 34 37 static synchronized void add(Thread hook) { 38 if(hooks == null) 39 throw new IllegalStateException ("Shutdown in progress"); 40 41 if (hook.isAlive()) 42 throw new IllegalArgumentException ("Hook already running"); 43 44 if (hooks.containsKey(hook)) 45 throw new IllegalArgumentException ("Hook previously registered"); 46 47 hooks.put(hook, hook); 48 } 49 50 53 static synchronized boolean remove(Thread hook) { 54 if(hooks == null) 55 throw new IllegalStateException ("Shutdown in progress"); 56 57 if (hook == null) 58 throw new NullPointerException (); 59 60 return hooks.remove(hook) != null; 61 } 62 63 67 public void run() { 68 Collection<Thread > threads; 69 synchronized(ApplicationShutdownHooks .class) { 70 threads = hooks.keySet(); 71 hooks = null; 72 } 73 74 for (Thread hook : threads) { 75 hook.start(); 76 } 77 for (Thread hook : threads) { 78 try { 79 hook.join(); 80 } catch (InterruptedException x) { } 81 } 82 } 83 } 84 85 | Popular Tags |