KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > lang > StartupHelper


1 /*
2  * All content copyright (c) 2003-2007 Terracotta, Inc., except as may otherwise be noted in a separate copyright
3  * notice. All rights reserved.
4  */

5 package com.tc.lang;
6
7 import java.lang.reflect.Field JavaDoc;
8
9 /**
10  * The purpose of this class to execute a startup action (ie. "start the server", or "start the client", etc) in the
11  * specified thread group. The side effect of doing this is that any more threads spawned by the startup action will
12  * inherit the given thread group. It is somewhat fragile, and sometimes impossible (see java.util.Timer) to be explicit
13  * about the thread group when spawning threads <br>
14  * <br>
15  * XXX: At the moment, this class uses a hack of adjusting the current thread's group to the desired target group.
16  * A nicer approach would be to start a new thread in the desiered target group and run the action in that thread and
17  * join() it, except that can introduce locking problems (see MNK-65)
18  */

19 public class StartupHelper {
20
21   private final StartupAction action;
22   private final ThreadGroup JavaDoc targetThreadGroup;
23
24   public StartupHelper(ThreadGroup JavaDoc threadGroup, StartupAction action) {
25     this.targetThreadGroup = threadGroup;
26     this.action = action;
27   }
28
29   public void startUp() {
30     Thread JavaDoc currentThread = Thread.currentThread();
31     ThreadGroup JavaDoc origThreadGroup = currentThread.getThreadGroup();
32
33     setThreadGroup(currentThread, targetThreadGroup);
34
35     Throwable JavaDoc actionError = null;
36     try {
37       action.execute();
38     } catch (Throwable JavaDoc 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 JavaDoc;
51   }
52
53   private static void setThreadGroup(Thread JavaDoc thread, ThreadGroup JavaDoc group) {
54     try {
55       Field JavaDoc groupField = thread.getClass().getDeclaredField("group");
56       groupField.setAccessible(true);
57       groupField.set(thread, group);
58     } catch (Exception JavaDoc e) {
59       if (e instanceof RuntimeException JavaDoc) { throw (RuntimeException JavaDoc) e; }
60       throw new RuntimeException JavaDoc(e);
61     }
62   }
63
64 }
65
Popular Tags