KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > EDU > oswego > cs > dl > util > concurrent > TimedCallable


1 /*
2   TimedCallable.java
3   
4   Originally written by Joseph Bowbeer and released into the public domain.
5   This may be used for any purposes whatsoever without acknowledgment.
6  
7   Originally part of jozart.swingutils.
8   Adapted by Doug Lea for util.concurrent.
9
10   History:
11   Date Who What
12   11dec1999 dl Adapted for util.concurrent
13
14  */

15
16 package EDU.oswego.cs.dl.util.concurrent;
17
18 /**
19  * TimedCallable runs a Callable function for a given length of time.
20  * The function is run in its own thread. If the function completes
21  * in time, its result is returned; otherwise the thread is interrupted
22  * and an InterruptedException is thrown.
23  * <p>
24  * Note: TimedCallable will always return within the given time limit
25  * (modulo timer inaccuracies), but whether or not the worker thread
26  * stops in a timely fashion depends on the interrupt handling in the
27  * Callable function's implementation.
28  *
29  * @author Joseph Bowbeer
30  * @version 1.0
31  *
32  * <p>[<a HREF="http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html"> Introduction to this package. </a>]
33
34  */

35
36 public class TimedCallable extends ThreadFactoryUser implements Callable {
37
38   private final Callable function;
39   private final long millis;
40   
41   public TimedCallable(Callable function, long millis) {
42     this.function = function;
43     this.millis = millis;
44   }
45   
46   public Object JavaDoc call() throws Exception JavaDoc {
47     
48     FutureResult result = new FutureResult();
49
50     Thread JavaDoc thread = getThreadFactory().newThread(result.setter(function));
51    
52     thread.start();
53     
54     try {
55       return result.timedGet(millis);
56     }
57     catch (InterruptedException JavaDoc ex) {
58       /* Stop thread if we were interrupted or timed-out
59          while waiting for the result. */

60       thread.interrupt();
61       throw ex;
62     }
63   }
64 }
65
Popular Tags