Spring @Async with the future

I am new to java.util.concurrent.Future and ask a few questions. If I call a service using Future, how do I know which element was used to call the service?

Here is an example:

  • For each identifier, I use java.util.concurrent.Future to call the service to populate some additional data.

    Collection< Future< ObjectX>> future = new ArrayList< Future< ObjectX>>(); 

    Edit ###

      List< ObjectY> serviceResult= new ArrayList< ObjectY>(); for (ObjectX obj: ids) { future.add(getAsyncInfo(obj); } //Because I have a lot of ids i need to call the service @async @Async public Future< ObjectY> getAsyncInfo(ObjectX obj){ return new AsyncResult<ObjectY>(callService(obj)); ... } 

Get an answer

 for (Future<ObjectY> futureResult : future) { serviceResult.add(futureResult.get()); } 

At this point, I have a list of results, and I don’t know which result belongs to what id

  ids.get(0).setResult(serviceResult.get(0))???? ids.get(0).setResult(serviceResult.get(1))???? ids.get(0).setResult(serviceResult.get(2))???? ... 

Thanks!

+4
source share
2 answers

I would do it this way

 class MyResult extends AsyncResult<Object> { Object id; public MyResult(Object id, Object res) { super(res); this.id = id; } public Object getId() { return id; } } @Async public MyResult getAsyncInfo(Object id) { Object res = callService(id); return new MyResult(id, res); } 

Now you know both the result and id. Identifier and result can be any type

+2
source

There are a few things you can do here.

  • Instead of Map < Map Collection should be Map ). The Map key should be some way that you can use to map to the original ObjectX .
  • Ask the service to return some information about its return value to help determine the identifier.

For 1, I thought something like this:

 //to kick off the tasks Map<ObjectX, Future<ObjectY>> futures = new HashMap<ObjectX, Future<ObjectY>>(); for (ObjectX id: ids) { futures.put(id, getAsyncInfo(id)); } //...some time later... //to fetch the results for(Map.Entry<ObjectX, Future<ObjectY>> entry : futures.entrySet()) { final ObjectX id = entry.getKey(); final Future<ObjectY> future = entry.getValue(); final ObjectY objY = future.get(); id.setResult(objY); } 
0
source

All Articles