1 | |
package org.paneris.bibliomania.metasearch.util; |
2 | |
|
3 | |
public class TimeoutThread extends Thread { |
4 | |
|
5 | |
private Thread t; |
6 | |
private int limitMillis, checkMillis, graceMillis; |
7 | |
|
8 | |
public static class ForcedStopException extends RuntimeException { |
9 | |
private static final long serialVersionUID = 1L; |
10 | |
} |
11 | |
|
12 | |
|
13 | |
|
14 | |
|
15 | |
|
16 | |
|
17 | |
|
18 | |
public TimeoutThread(Thread t, |
19 | 0 | int limitMillis, int checkMillis, int graceMillis) { |
20 | 0 | t.checkAccess(); |
21 | 0 | this.t = t; |
22 | 0 | this.limitMillis = limitMillis; |
23 | 0 | this.checkMillis = checkMillis; |
24 | 0 | this.graceMillis = graceMillis; |
25 | 0 | setDaemon(true); |
26 | 0 | } |
27 | |
|
28 | |
public TimeoutThread(Thread t, int limitMillis) { |
29 | 0 | this(t, limitMillis, 100, 1000); |
30 | 0 | } |
31 | |
|
32 | |
public void run() { |
33 | |
try { |
34 | 0 | Thread.sleep(limitMillis); |
35 | 0 | t.interrupt(); |
36 | 0 | Thread.sleep(checkMillis); |
37 | 0 | if (t.isAlive()) { |
38 | 0 | Thread.sleep(graceMillis); |
39 | 0 | t.stop(new ForcedStopException()); |
40 | |
} |
41 | |
} |
42 | 0 | catch (InterruptedException e) { |
43 | 0 | } |
44 | 0 | } |
45 | |
|
46 | |
public static TimeoutThread forCurrentThread(int limitMillis) { |
47 | 0 | TimeoutThread timer = new TimeoutThread(Thread.currentThread(), |
48 | |
limitMillis); |
49 | 0 | timer.start(); |
50 | 0 | return timer; |
51 | |
} |
52 | |
|
53 | |
public static void run(Runnable r, int limitMillis) { |
54 | 0 | TimeoutThread timer = forCurrentThread(limitMillis); |
55 | |
try { |
56 | 0 | r.run(); |
57 | |
} |
58 | |
finally { |
59 | 0 | timer.stop(); |
60 | 0 | } |
61 | 0 | } |
62 | |
} |