KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > snow > concurrent > InterruptableTask


1 package snow.concurrent;
2
3 import java.util.concurrent.*;
4 import java.util.*;
5
6 /** wraps a runnable into an interruptable task.
7   I.e. creates a thread that can be interrupted.
8      should only be interrupted when not stopping itself correctely with the Interrupter
9 */

10 public abstract class InterruptableTask <T> implements Callable<T>, Runnable JavaDoc
11 {
12   Thread JavaDoc thread;
13   final public Interrupter interrupter = new Interrupter(); // correct way to stop the thread
14
Future future; // set at submit
15
private boolean isExecuting = false;
16
17
18   public InterruptableTask()
19   {
20
21   } // Constructor
22

23   public boolean isExecuting() { return isExecuting; }
24
25   public final T call() throws Exception JavaDoc
26   {
27      if(this.interrupter.shouldStopEvaluation())
28      {
29        // never evaluates !
30
return null;
31      }
32
33      isExecuting = true;
34      thread = new Thread JavaDoc(this);
35      // wait until completion
36
try
37      {
38        thread.start();
39        thread.join();
40      }
41      catch(Exception JavaDoc e)
42      {
43        kill();
44        throw e;
45      }
46      finally
47      {
48        isExecuting = false;
49      }
50      return null;
51   }
52
53   /** use only if request stop has not succeded.
54      This kills the thread.
55      BE CAREFUL: if the therad calls EventQueue.invokeAndWait, and catch Exception without throwing them
56       the thread continues !!
57   */

58   public void kill()
59   {
60      if(thread!=null && thread.isAlive())
61      {
62        thread.interrupt(); // throws an exception that may be catched => not 100% stops
63
}
64
65      // thread.stop() // stops 100% but not safe ! deprecated !!
66
}
67
68   public void requestStop()
69   {
70      if(interrupter.shouldStopEvaluation())
71      {
72        // already cool stopped but still called => kill
73
kill();
74      }
75      else
76      {
77        // first attempt : cool stop
78
interrupter.stopEvaluation();
79      }
80   }
81
82
83 } // InterruptableTask
Popular Tags