Asynchronous and Parallel Processing Requests
A client can use the submit method instead of the execute method of Service to perform a remote invocation without waiting for the result. This allows the caller to make many asynchronous requests in parallel — with these requests being executed in parallel if the resources are available to do so. In addition to the method name and argument, the submit method takes a callback object that implements the ServiceInvocationHandler interface. This interface has a handleResponse method that is called with the method’s return value in the event of a normal response, and a handleError message that is called if an error occurs. The submit method returns an integer that uniquely identifies the particular call; this unique ID is passed as the second argument to the ServiceInvocationHandler methods, so that you can match the response with the request if need be.
To use the submit method, we first require a class implementing ServiceInvocationHandler. The handleResponse method displays the response and adds it to a total.
// Handler for Service Clients
static class AdderHandler implements ServiceInvocationHandler {
public void handleError(ServiceInvocationException e, int id) {
System.out.println("Error from " + id + ": " + e);
}
public void handleResponse(Serializable response, int id) {
System.out.println("Response from " + id + ": " + response);
_total += ((Double)response).doubleValue();
}
public double getTotal() {
return _total;
}
private double _total = 0;
}
Now we can invoke the submit method:
// Perform Asynchronous adds
AdderHandler handler = new AdderHandler();
for (int i=0; i < 10; i++) {
s.submit("add", new Object[] { new Double(i), new Double(i) }, handler);
}
// Wait until all the invocations have returned
s.waitUntilInactive(0);
System.out.println("Total: " + handler.getTotal());
This code first creates a ServiceInvocationHandler, and then it calls submit several times. To wait for all the responses to arrive, the call to waitUntilInactive causes the current thread to wait until all outstanding requests have finished. The argument is a timeout value in milliseconds; an argument of zero means wait indefinitely.