I ran into this piece of code when learning to write an asynchronous client of a web service. I am trying to understand how "new AsyncHandler<Inventory>() {...}"
is used here. I am relatively new to Java, and there are a few things that I don't understand:
- AsyncHandler is from
javax.xml.ws.AsyncHandler
, and how Inventory, an local or custom object can be part of it. What doesAsyncHandler<Inventory>
mean? - Is the use of "new
AsyncHandler<Inventory>() {...}
" an instantiation or implementation of the class AsyncHandler? - what is the relationship of handleResponse and AsyncHandler?
Here is the code:
public class StockWebServiceClientCallbackMainMyCopy {
private static Logger log = Logger.getLogger(StockWebServiceClientCallbackMain.class.getName());
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
final Stock stockPort = new StockService().getStockPort();
log.info("Got StockService port successfully");
final int thresh = 2;
// TODO: (53.01) Call async method passing in callback method
// In the callback method, print out all the items and exit
// Important: call System.exit() from callback
stockPort.getStockItemsWithQuantityLessThanAsync(thresh, new AsyncHandler<Inventory>(){
@Override
public void handleResponse(Response<Inventory> response) {
log.info("Callback invoked");
try{
Inventory inventory = response.get();
for (Item item : inventory.getItems()){
System.out.println(item.getProductId() + " " + item.getQuantity());
}
System.exit(0);
}
catch(Exception e){
e.printStackTrace();
}
}
});
// TODO: (53.02) Note simulation of other activity using Thread.sleep()
while (true){
try{
Thread.sleep(1000);
} catch (InterruptedException e){
// ok
}
}
}
}