Reputation: 2353
I have created the following FutureTask method to run a method asynchronously.
public FutureTask<Object> SendAggregateEventAsync(final
com.Company.Product.SDK.Device.AggregateEvent.ClassObject
request)
{
FutureTask<Object> futureTask;
futureTask = new FutureTask<Object>(new Runnable() {
public void run()
{
try {
SendAggregateEvent(request);
} catch (ResponseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, null);
return futureTask;
}
public void SendAggregateEvent(
com.Company.Product.SDK.Device.AggregateEvent.ClassObject
request) throws ResponseException
{
try
{
if(request == null) throw new IllegalArgumentException("request");
String[] s_array = new String[0];
s_array[0] = "EventTime";
String namespace = "http://Product.Company.com/" +
"v1.0/Device/AggregateEvent";
IBindingFactory factory;
factory = BindingDirectory.getFactory(
com.Compant.Product.SDK.Device.AggregateEvent.
ClassObject.class);
String message = ChangeDatesToUTC(MessageHelper.
SerializeObject(factory, request), s_array, namespace);
SendMessage(message);
} catch (JiBXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
In order to compile I must catch the ResponseException in the FutureTask, but it is vital that this ResponseException be thrown to the implementing application and not caught by FutureTask. Is there a way around this where I can throw this exception out of FutureTask?
Upvotes: 3
Views: 1629
Reputation: 691715
Pass a Callable to the constructor instead of passing a Runnable, and you won't have to catch the exception anymore:
futureTask = new FutureTask<Object>(new Callable() {
public Object call() throws ResponseException {
SendAggregateEvent(request);
return null;
}
};
(but the generic type of the FutureTask should be Void
rather than Object
).
If a ResponseException is thrown by call()
, the get()
method of the FutureTask will throw an ExecutionException, and the cause of this exception will be the ResponseException.
That said, shouldn't you simply submit the Callable to an ExecutorService, and let it create a Future for you? Also try to respect the Java naming conventions, and remove the throws clause from your method, since it doesn't throw any exception. The naming is also bad: your method doesn't send anything. It only creates a FutureTask which, when executed, will send an event.
Upvotes: 5