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 int limitMillis, int checkMillis, int graceMillis) {
20 t.checkAccess();
21 this.t = t;
22 this.limitMillis = limitMillis;
23 this.checkMillis = checkMillis;
24 this.graceMillis = graceMillis;
25 setDaemon(true);
26 }
27
28 public TimeoutThread(Thread t, int limitMillis) {
29 this(t, limitMillis, 100, 1000);
30 }
31
32 public void run() {
33 try {
34 Thread.sleep(limitMillis);
35 t.interrupt();
36 Thread.sleep(checkMillis);
37 if (t.isAlive()) {
38 Thread.sleep(graceMillis);
39 t.stop(new ForcedStopException());
40 }
41 }
42 catch (InterruptedException e) {
43 }
44 }
45
46 public static TimeoutThread forCurrentThread(int limitMillis) {
47 TimeoutThread timer = new TimeoutThread(Thread.currentThread(),
48 limitMillis);
49 timer.start();
50 return timer;
51 }
52
53 public static void run(Runnable r, int limitMillis) {
54 TimeoutThread timer = forCurrentThread(limitMillis);
55 try {
56 r.run();
57 }
58 finally {
59 timer.stop();
60 }
61 }
62 }