Home

 

Invoking Web services asynchronously

With JAX-WS, Web services can be called both synchronously and asynchronously. JAX-WS adds support for both a polling mechanism and callback mechanism when calling Web services asynchronously. Using a polling model, a client can issue a request and get a response object back, which is polled to determine whether the server has responded. When the server responds, the actual response is retrieved. Using the polling model, the client can continue to process other work without waiting for a response to return.

Using the callback model, the client provides a callback handler to accept and process the inbound response object. Both the polling and callback models enable the client to focus on continuing to process work while providing for a more dynamic and efficient model to invoke Web services.

For example, a Web service interface has methods for both synchronous and asynchronous requests (Example | 8-2). Asynchronous requests are identified in bold.

Example 18-2 Asynchronous Methods in the Web service interface

@WebService
public interface CreditRatingService {
	// sync operation
	Score getCreditScore(Customer customer);
	// async operation with polling
	Response<Score> getCreditScoreAsync(Customer customer);
	// async operation with callback
	Future<?> getCreditScoreAsync(Customer customer, 
											AsyncHandler<Score> handler);
}

The asynchronous invocation that uses the callback mechanism requires an additional input by the client programmer. The callback handler is an object that contains the application code that is executed when an asynchronous response is received. Example | 8-3 shows an asynchronous callback handler.

Example 18-3 Asynchronous callback handler

CreditRatingService svc = ...;

Future<?> invocation = svc.getCreditScoreAsync(customerFred,
	new AsyncHandler<Score>() {
		public void handleResponse(Response<Score> response) {
			Score score = response.get();
			// do work here...
		}
	}
);

Example | 8-4 shows an asynchronous polling client.

Example 18-4 Asynchronous polling

CreditRatingService svc = ...;
Response<Score> response = svc.getCreditScoreAsync(customerFred);

while (!response.isDone()) {
	// do something while we wait
}

// no cast needed, thanks to generics
Score score = response.get();

ibm.com/redbooks