01: /*
02: TimedCallable.java
03:
04: Originally written by Joseph Bowbeer and released into the public domain.
05: This may be used for any purposes whatsoever without acknowledgment.
06:
07: Originally part of jozart.swingutils.
08: Adapted by Doug Lea for util.concurrent.
09:
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
37: Callable {
38:
39: private final Callable function;
40: private final long millis;
41:
42: public TimedCallable(Callable function, long millis) {
43: this .function = function;
44: this .millis = millis;
45: }
46:
47: public Object call() throws Exception {
48:
49: FutureResult result = new FutureResult();
50:
51: Thread thread = getThreadFactory().newThread(
52: result.setter(function));
53:
54: thread.start();
55:
56: try {
57: return result.timedGet(millis);
58: } catch (InterruptedException ex) {
59: /* Stop thread if we were interrupted or timed-out
60: while waiting for the result. */
61: thread.interrupt();
62: throw ex;
63: }
64: }
65: }
|