Define a callback interface (if one isn't already available) and make your method take the interface as a parameter. The method will go off and do its work, and when it's finished, it calls the callback.
Example:
int synchronousMethod(int arg0, String arg1) {
int result = doStuff();
return result;
}
becomes
void asynchronousMethod(int arg0, String arg1, Callback callback) {
try {
int result = doStuff();
} catch (Throwable t) {
callback.onFailure(t);
return;
}
callback.onSuccess(result);
}
where Callback
is something like
interface Callback {
onSuccess(int result);
onFailure(Throwable t);
}
It's preferable to use generic types for the Callback
result (GWT, for example, uses a generic AsyncCallback<ResultType>
that is identical to the interface above), but since generics aren't available in 1.4, you can either use Object
and cast or have different Callback
interfaces for different returns. Compare with any of the *Listener
interfaces in Swing/AWT.