0

I have a Collection of Objects. I have to call a method on this collections of objects which returns a Future. Right now I use the get() on the Future so that it make the operation Synchronous. How can I convert it to Async?

for (Summary summary : summaries) {
    acmResponseFuture(summary.getClassification()));
    String classification = summary.getClassification();
    // this is a call which return Future and which is a sync call now
    AcmResponse acmResponse = acmResponseFuture(classification).get();
    if (acmResponse != null && acmResponse.getAcmInfo() != null) {
        summary.setAcm(mapper.readValue(acmResponse.getAcmInfo().getAcm(), Object.class));

    }
    summary.setDataType(DATA_TYPE);
    summary.setApplication(NAME);
    summary.setId(summary.getEntityId());
    summary.setApiRef(federatorConfig.getqApiRefUrl() + summary.getEntityId());
}
ssuperczynski
  • 3,190
  • 3
  • 44
  • 61
allthenutsandbolts
  • 1,513
  • 1
  • 13
  • 34

1 Answers1

0

How about collecting all of the Future instances before waiting on the synchronous call?

    Collection<Future<AcmResponse>> futures = new ArrayList<>();
    for (Summary summary : summaries) {
        acmResponseFuture(summary.getClassification()));
        String classification = summary.getClassification();
        // this is a call which return Future...
        futures.add(acmResponseFuture(classification));
    }

    for (Future<AcmResponse> future : futures) {
        // ...and which is a sync call now
        AcmResponse acmResponse = future.get();
        if (acmResponse != null && acmResponse.getAcmInfo() != null) {
            summary.setAcm(mapper.readValue(acmResponse.getAcmInfo().getAcm(), Object.class));

        }
        summary.setDataType(DATA_TYPE);
        summary.setApplication(NAME);
        summary.setId(summary.getEntityId());
        summary.setApiRef(federatorConfig.getqApiRefUrl() + summary.getEntityId());
    }

Obviously you'll have to sort out updating the summaries; but the idea is you want all the futures at once before making any calls to them. Put the futures & summaries into a map...

jaco0646
  • 15,303
  • 7
  • 59
  • 83
  • How is this different from the original code ? I need to avoid get on the future and use some of the Async features – allthenutsandbolts Mar 03 '16 at 20:48
  • Presumably `acmResponseFuture(classification)` is kicking off the async work. `Future.get()` is simply waiting for that work to complete. – jaco0646 Mar 03 '16 at 20:50