在Collection上调用Async操作

时间:2016-03-03 17:02:22

标签: java twitter-finagle

我有一个对象集合。我必须在这个返回Future的对象集合上调用一个方法。现在我在Future上使用get(),这样它就可以使操作同步。如何将其转换为异步?

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());
}

1 个答案:

答案 0 :(得分:0)

如何在等待同步调用之前收集所有Future个实例?

    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());
    }

显然你必须整理更新摘要;但是这个想法是你在打电话给他们之前想要所有的期货。把期货&amp;摘要到地图......