File: TimedCallable.java

package info (click to toggle)
concurrent-dfsg 1.3.4-4
  • links: PTS, VCS
  • area: main
  • in suites: buster, jessie, jessie-kfreebsd, squeeze, stretch, wheezy
  • size: 976 kB
  • ctags: 2,018
  • sloc: java: 10,704; xml: 49; makefile: 12
file content (64 lines) | stat: -rw-r--r-- 1,824 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
  TimedCallable.java
  
  Originally written by Joseph Bowbeer and released into the public domain.
  This may be used for any purposes whatsoever without acknowledgment.
 
  Originally part of jozart.swingutils.
  Adapted by Doug Lea for util.concurrent.

  History:
  Date       Who                What
  11dec1999   dl                Adapted for util.concurrent

 */

package EDU.oswego.cs.dl.util.concurrent;

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

 */

public class TimedCallable extends ThreadFactoryUser implements Callable {

  private final Callable function;
  private final long millis;
  
  public TimedCallable(Callable function, long millis) {
    this.function = function;
    this.millis = millis;
  }
  
  public Object call() throws Exception {
    
    FutureResult result = new FutureResult();

    Thread thread = getThreadFactory().newThread(result.setter(function));
   
    thread.start();
    
    try {
      return result.timedGet(millis);
    }
    catch (InterruptedException ex) {
      /* Stop thread if we were interrupted or timed-out
         while waiting for the result. */
      thread.interrupt();
      throw ex;
    }
  }
}