I've been considering a general purpose generic / cancellable interface for asynchronous request / responses. The requirements are as follows, it must:
- Support asynchronous calls
- Be cancellable
- Be generic
- Support request / response
- Support either returning in the current thread or processing the response in another response
So here's my first stab:
interface AsyncOperation<INPUT, OUTPUT> {
Future<OUTPUT> execute(INPUT in, AsyncCallback<OUTPUT> callback);
}
interface AsyncCallback<OUTPUT> {
void done(OUTPUT output);
}
Usage:
// completely async operation
operation.execute("Test", new AsyncCallback<String> {
public void done(String output) {
// process result...
}
});
// sync operation with cancellation after timeout
Future<String> future = operation.execute("Test", null);
try {
String result = future.get(1000);
} catch(TimeoutException ex) {
future.cancel();
}
Disadvantages
- It's complicated
- It only supports a single request parameter -- not too concerned about this one
- The single 'done' means that exceptions have to be communicated through the 'done', this could be solved by having an onSuccess and onException (and onFinally?) in AsyncCallback but it would make it even more verbose
For some context, the Google Protocol Buffers service methods follow a relatively similar model:
void [methodname](RpcController controller,
[RequestClass] request, RpcCallback<[ResponseClass]> callback);
Any better ideas?