【问题标题】:Calling a Async operation on Collection在 Collection 上调用异步操作
【发布时间】:2016-06-17 03:30:33
【问题描述】:

我有一个对象集合。我必须在这个返回 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());
}

【问题讨论】:

  • 为什么它是一个未来?
  • 它是一个我们无法控制的外部 API。通常我们只需要传递一个 Record 给它,但是在这种情况下我们可以传递一个集合

标签: java twitter-finagle


【解决方案1】:

在等待同步调用之前收集所有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());
    }

显然,您必须整理更新摘要;但想法是在调用所有期货之前,您需要一次获得所有期货。将未来和摘要放入地图...

【讨论】:

  • 这与原始代码有何不同?我需要避免进入未来并使用一些异步功能
  • 大概acmResponseFuture(classification) 正在启动异步工作。 Future.get() 只是在等待这项工作完成。
猜你喜欢
  • 1970-01-01
  • 2011-11-30
  • 2017-12-16
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多