1 4 package com.tc.util; 5 6 import java.util.ArrayList ; 7 import java.util.List ; 8 9 public class CommonShutDownHook implements Runnable { 10 private static final List runnables = new ArrayList (); 11 private static Thread hooker; 13 public static void addShutdownHook(Runnable r) { 14 if (r == null) { throw new NullPointerException ("Shutdown hook cannot be null"); } 15 synchronized (runnables) { 16 runnables.add(r); 17 18 if (hooker == null) { 19 hooker = new Thread (new CommonShutDownHook()); 20 hooker.setName("CommonShutDownHook"); 21 hooker.setDaemon(true); 22 Runtime.getRuntime().addShutdownHook(hooker); 23 } 24 } 25 } 26 27 public void run() { 28 final Runnable [] hooks; 30 synchronized (runnables) { 31 hooks = (Runnable []) runnables.toArray(new Runnable [runnables.size()]); 32 } 33 34 for (int i = 0; i < hooks.length; i++) { 35 Runnable r = hooks[i]; 36 Thread.currentThread().setName("CommonShutDownHook - " + r); 37 38 try { 39 r.run(); 40 } catch (Throwable t) { 41 t.printStackTrace(); 42 } 43 } 44 } 45 } 46 | Popular Tags |