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 package org.apache.commons.httpclient.util;
31
32 /***
33 * <p>
34 * Executes a task with a specified timeout.
35 * </p>
36 * @author Ortwin Glueck
37 * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
38 * @version $Revision: 291181 $
39 * @since 2.0
40 */
41 public final class TimeoutController {
42
43 /***
44 * Do not instantiate objects of this class. Methods are static.
45 */
46 private TimeoutController() {
47 }
48
49 /***
50 * Executes <code>task</code>. Waits for <code>timeout</code>
51 * milliseconds for the task to end and returns. If the task does not return
52 * in time, the thread is interrupted and an Exception is thrown.
53 * The caller should override the Thread.interrupt() method to something that
54 * quickly makes the thread die or use Thread.isInterrupted().
55 * @param task The thread to execute
56 * @param timeout The timeout in milliseconds. 0 means to wait forever.
57 * @throws TimeoutException if the timeout passes and the thread does not return.
58 */
59 public static void execute(Thread task, long timeout) throws TimeoutException {
60 task.start();
61 try {
62 task.join(timeout);
63 } catch (InterruptedException e) {
64
65 }
66 if (task.isAlive()) {
67 task.interrupt();
68 throw new TimeoutException();
69 }
70 }
71
72 /***
73 * Executes <code>task</code> in a new deamon Thread and waits for the timeout.
74 * @param task The task to execute
75 * @param timeout The timeout in milliseconds. 0 means to wait forever.
76 * @throws TimeoutException if the timeout passes and the thread does not return.
77 */
78 public static void execute(Runnable task, long timeout) throws TimeoutException {
79 Thread t = new Thread(task, "Timeout guard");
80 t.setDaemon(true);
81 execute(t, timeout);
82 }
83
84 /***
85 * Signals that the task timed out.
86 */
87 public static class TimeoutException extends Exception {
88 /*** Create an instance */
89 public TimeoutException() {
90 }
91 }
92 }