Guava ListenableFuture找不到源对象

时间:2014-07-12 22:22:26

标签: java guava

使用Guava的ListenableFuture时,如何知道失败的任务。 实施例

FutureCallback<AsyncHTTPResponse> future = new FutureCallback<AsyncHTTPResponse>() {
  @Override
  public void onFailure(Throwable arg0)
  {
     // In this block I do not know who succeeded. We could create custom 
     // exceptions and put the object in there, but what if we are not
     // directly causing the exception. Seems like there should be an easy
     // way to get the callable task that failed to produce a success result
  }

  @Override
  public void onSuccess(AsyncHTTPResponse arg0)
  {
    // In this block I know the original object that succeded
  }
};

所以在这个例子中,我找不到给出URL的callable来尝试通过http获取一些数据。因此,失败不知道哪个URL失败了。当然有一些解决方法,比如在表格中记录期货和网址,但有没有更简洁的方法来使用框架为你做这个?

1 个答案:

答案 0 :(得分:0)

我经常看到的解决方案是为每个请求创建一个新的回调实例:

final URL url = ...;
ListenableFuture<AsyncHTTPResponse> future = makeRequest(url);
addCallback(future, new FutureCallback<AsyncHTTPResponse>() {
  @Override
  public void onFailure(Throwable e)
  {
    // do something with url
  }

  ...
});