1 5 package com.tc.lang; 6 7 import java.lang.reflect.Field ; 8 9 19 public class StartupHelper { 20 21 private final StartupAction action; 22 private final ThreadGroup targetThreadGroup; 23 24 public StartupHelper(ThreadGroup threadGroup, StartupAction action) { 25 this.targetThreadGroup = threadGroup; 26 this.action = action; 27 } 28 29 public void startUp() { 30 Thread currentThread = Thread.currentThread(); 31 ThreadGroup origThreadGroup = currentThread.getThreadGroup(); 32 33 setThreadGroup(currentThread, targetThreadGroup); 34 35 Throwable actionError = null; 36 try { 37 action.execute(); 38 } catch (Throwable t) { 39 actionError = t; 40 } finally { 41 setThreadGroup(currentThread, origThreadGroup); 42 } 43 44 if (actionError != null) { 45 targetThreadGroup.uncaughtException(currentThread, actionError); 46 } 47 } 48 49 public interface StartupAction { 50 void execute() throws Throwable ; 51 } 52 53 private static void setThreadGroup(Thread thread, ThreadGroup group) { 54 try { 55 Field groupField = thread.getClass().getDeclaredField("group"); 56 groupField.setAccessible(true); 57 groupField.set(thread, group); 58 } catch (Exception e) { 59 if (e instanceof RuntimeException ) { throw (RuntimeException ) e; } 60 throw new RuntimeException (e); 61 } 62 } 63 64 } 65 | Popular Tags |