KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com4j > Task


1 package com4j;
2
3 import java.util.concurrent.Callable JavaDoc;
4
5 /**
6  * Used to execute a chunk of code from {@link ComThread}.
7  *
8  * @author Kohsuke Kawaguchi (kk@kohsuke.org)
9  */

10 abstract class Task<T> implements Callable JavaDoc<T> {
11     public abstract T call();
12
13
14     /**
15      * Executes the task.
16      */

17     public final T execute() {
18         if( ComThread.isComThread() )
19             // if invoked from within ComThread, execute it at once
20
return call();
21         else
22             // otherwise schedule the execution and block
23
return ComThread.get().execute(this);
24     }
25
26     public final T execute(ComThread t) {
27         if(Thread.currentThread()==t)
28             // if invoked from within ComThread, execute it at once
29
return call();
30         else
31             // otherwise schedule the execution and block
32
return t.execute(this);
33     }
34
35     /**
36      * Called from {@link ComThread} to run the task.
37      */

38     final synchronized void invoke() {
39         assert next!=null;
40         next = null;
41
42         result = null;
43         exception = null;
44         try {
45             result = call();
46         } catch( RuntimeException JavaDoc e ) {
47             exception = e;
48         }
49
50         // let the calling thread know that we are done.
51
notify();
52     }
53
54     /**
55      * Managed by {@link ComThread} to form a linked list from
56      * {@link ComThread#taskList}.
57      */

58     Task<?> next;
59
60     /**
61      * Managed by {@link ComThread} to pass the return value
62      * across threads.
63      */

64     T result;
65
66     /**
67      * Managed by {@link ComThread} to pass the exception
68      * across threads.
69      */

70     RuntimeException JavaDoc exception;
71 }
72
Popular Tags