3 import java.util.logging.*;
4 import java.lang.reflect.*;
6 public class ThreadContext extends ThreadGroup {
7 private Logger logger = Logger.getLogger("dolda.jsvc.context");
8 private ThreadGroup workers;
10 private final ServerContext ctx;
11 public final Responder root;
13 public ThreadContext(ThreadGroup parent, String name, ServerContext ctx, Class<?> bootclass) {
14 super((parent == null)?(Thread.currentThread().getThreadGroup()):parent, name);
16 workers = new ThreadGroup(this, "Worker threads") {
17 public void uncaughtException(Thread t, Throwable e) {
18 logger.log(Level.SEVERE, "Worker thread terminated with an uncaught exception", e);
21 root = bootstrap(bootclass);
24 public void uncaughtException(Thread t, Throwable e) {
25 logger.log(Level.SEVERE, "Service thread " + t.toString() + " terminated with an uncaught exception", e);
28 public ServerContext server() {
32 public void shutdown() {
33 if(root instanceof ContextResponder)
34 ((ContextResponder)root).destroy();
38 long now = System.currentTimeMillis();
39 if(now - last > 10000) {
43 Thread[] th = new Thread[1];
48 } catch(InterruptedException e) {
49 logger.log(Level.WARNING, "Interrupted while trying to shut down all service threads. Some may remain.", e);
54 public RequestThread respond(Request req) {
55 return(new RequestThread(root, req, workers, "Worker thread " + reqs++));
58 private Responder bootstrap(final Class<?> bootclass) {
59 final Throwable[] err = new Throwable[1];
60 final Responder[] res = new Responder[1];
61 Thread boot = new Thread(this, "JSvc boot thread") {
64 Method cm = bootclass.getMethod("responder");
65 Object resp = cm.invoke(null);
66 if(!(resp instanceof Responder))
67 throw(new ClassCastException("JSvc bootstrapper did not return a responder"));
68 res[0] = (Responder)resp;
69 } catch(NoSuchMethodException e) {
70 logger.log(Level.SEVERE, "Invalid JSvc bootstrapper specified", e);
72 } catch(IllegalAccessException e) {
73 logger.log(Level.SEVERE, "Invalid JSvc bootstrapper specified", e);
75 } catch(InvocationTargetException e) {
76 logger.log(Level.SEVERE, "JSvc bootstrapper failed", e);
84 } catch(InterruptedException e) {
85 logger.log(Level.WARNING, "Interrupted during bootstrapping", e);
87 Thread.currentThread().interrupt();
90 throw(new RuntimeException(err[0]));
92 logger.log(Level.SEVERE, "No responder returned in spite of no error having happened.");
93 throw(new NullPointerException("No responder returned in spite of no error having happened."));
98 public static ThreadContext current() {
99 for(ThreadGroup tg = Thread.currentThread().getThreadGroup(); tg != null; tg = tg.getParent()) {
100 if(tg instanceof ThreadContext)
101 return((ThreadContext)tg);