01: package com.sun.portal.common.util;
02:
03: public class TimeBoundExecutor {
04: private boolean _destroyed = false;
05:
06: public TimeBoundExecutor() {
07: }
08:
09: // timeout in milliseconds
10: public void run(TimeBoundRunnable runnable, int timeout)
11: throws TimeoutException, TimeBoundRunnableException {
12: if (_destroyed) {
13: throw new IllegalStateException(
14: "TimeBoundExecutor.run - Executor destroyed");
15: }
16: if (timeout == -1) {
17: runnable.run();
18: } else {
19: TBRunnable tbRunnable = new TBRunnable(runnable);
20: Thread thread = new Thread(tbRunnable);
21: thread.start();
22: try {
23: thread.join(timeout);
24: } catch (InterruptedException ex) {
25: }
26:
27: if (!tbRunnable.isDone()) {
28: throw new TimeoutException();
29: }
30: TimeBoundRunnableException ex = tbRunnable.getException();
31: if (ex != null) {
32: throw ex;
33: }
34: }
35: }
36:
37: public void destroy() {
38: _destroyed = true;
39: }
40:
41: private static class TBRunnable implements Runnable {
42: private TimeBoundRunnable _runnable;
43: private boolean _finished;
44: private TimeBoundRunnableException _exception;
45:
46: private TBRunnable(TimeBoundRunnable runnable) {
47: _runnable = runnable;
48: }
49:
50: public void run() {
51: try {
52: _runnable.run();
53: } catch (TimeBoundRunnableException ex) {
54: _exception = ex;
55: } finally {
56: _finished = true;
57: }
58: }
59:
60: public boolean isDone() {
61: return _finished;
62: }
63:
64: public TimeBoundRunnableException getException() {
65: return _exception;
66: }
67:
68: }
69:
70: }
|