1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 package de.bea.domingo.service;
24
25 import java.lang.reflect.InvocationTargetException;
26 import java.lang.reflect.Method;
27
28 /***
29 * Invocation task for worker thread.
30 *
31 * <p>An Invocation task is an implementation of the <code>Runnable</code>
32 * interface where the <code>run()</code> method executes a method on an
33 * object with an array of arguments.</p>
34 * <p>This task is used to delegate method calls to worker threads in a generic
35 * way.</p>
36 *
37 * @author <a href=mailto:kriede@users.sourceforge.net>Kurt Riede</a>
38 */
39 public final class InvocationTask implements Runnable {
40
41 /*** Object to invoke method on. */
42 private Object fObject = null;
43
44 /*** Method to invoke. */
45 private Method fMethod = null;
46
47 /*** Arguments to the method invocation. */
48 private Object[] fArgs = null;
49
50 /*** Result of the method invocation. */
51 private Object fResult = null;
52
53 /*** Optionally thrown Throwable of the method invocation. */
54 private Throwable fThrowable = null;
55
56 /*** Indicates if the task is completed. */
57 private boolean fCompleted = false;
58
59 private Object mutex = new Object();
60
61 /***
62 * Constructor.
63 *
64 * @param object the object to invoke the method on
65 * @param method the method to invoke
66 * @param args the arguments for the method
67 */
68 InvocationTask(final Object object, final Method method, final Object[] args) {
69 fObject = object;
70 fMethod = method;
71 fArgs = args;
72 }
73
74 /***
75 * Returns the result from the method invocation.
76 *
77 * @return result from invoked method
78 */
79 public Object getResult() {
80 synchronized (mutex) {
81 return fResult;
82 }
83 }
84
85 /***
86 * Returns the optional thrown throwable.
87 *
88 * @return Returns the optional throwable.
89 */
90 protected Throwable getThrowable() {
91 return fThrowable;
92 }
93
94 /***
95 * Invokes the method.
96 *
97 * @see java.lang.Runnable#run()
98 */
99 public void run() {
100 synchronized (mutex) {
101 try {
102 fResult = fMethod.invoke(fObject, fArgs);
103 } catch (InvocationTargetException e) {
104 fThrowable = e.getTargetException();
105 } catch (Throwable t) {
106 fThrowable = t;
107 } finally {
108 fCompleted = true;
109 mutex.notifyAll();
110 }
111 }
112 }
113
114 /***
115 * Indicates whether the task is completed.
116 *
117 * @return <code>true</code> if the task is completed, else
118 * <code>false</code>
119 */
120 public boolean isCompleted() {
121 return fCompleted;
122 }
123 }