File D:\maven-qcr-plugin-testsunitaires\qcr4java\h2-1.3.170-sources\target\site\qc\lecode\util\Task.java.html

1 /*
2 * Copyright 2004-2011 H2 Group. Multiple-Licensed under the H2 License,
3 * Version 1.0, and under the Eclipse Public License, Version 1.0
4 * (http://h2database.com/html/license.html).
5 * Initial Developer: H2 Group
6 */
7 package org.h2.util;
8
9 /**
10 * A method call that is executed in a separate thread. If the method throws an
11 * exception, it is wrapped in a RuntimeException.
12 */
13 public abstract class Task implements Runnable {
14
15 /**
16 * A flag indicating the get() method has been called.
17 */
18 protected volatile boolean stop;
19
20 /**
21 * The result, if any.
22 */
23 protected Object result;
24
25 private Thread thread;
26
27 private Exception ex;
28
29 /**
30 * The method to be implemented.
31 *
32 * @throws Exception any exception is wrapped in a RuntimeException
33 */
34 public abstract void call() throws Exception;
35
36 public void run() {
37 try {
38 call();
39 } catch (Exception e) {
40 this.ex = e;
41 }
42 }
43
44 /**
45 * Start the thread.
46 *
47 * @return this
48 */
49 public Task execute() {
50 return execute(getClass().getName());
51 }
52
53 /**
54 * Start the thread.
55 *
56 * @param threadName the name of the thread
57 * @return this
58 */
59 public Task execute(String threadName) {
60 thread = new Thread(this, threadName);
61 thread.setDaemon(true);
62 thread.start();
63 return this;
64 }
65
66 /**
67 * Calling this method will set the stop flag and wait until the thread is
68 * stopped.
69 *
70 * @return the result, or null
71 * @throws RuntimeException if an exception in the method call occurs
72 */
73 public Object get() {
74 Exception e = getException();
75 if (e != null) {
76 throw new RuntimeException(e);
77 }
78 return result;
79 }
80
81 /**
82 * Get the exception that was thrown in the call (if any).
83 *
84 * @return the exception or null
85 */
86 public Exception getException() {
87 stop = true;
88 if (thread == null) {
89 throw new IllegalStateException("Thread not started");
90 }
91 try {
92 thread.join();
93 } catch (InterruptedException e) {
94 // ignore
95 }
96 if (ex != null) {
97 return ex;
98 }
99 return null;
100 }
101
102 }
103