Java中等待异步调用完成后再继续进行

3
我有一个情况,在其中调用一个方法,该方法触发异步HTTP REST调用(稍后将状态发送到另一个端点),然后再继续执行。我希望该方法等待,直到我收到来自端点的响应,检查我得到的状态并继续执行。我正在寻找Java中可行的解决方案。任何伪代码或实现都将很有帮助。
此处看到了类似的情况,但对其不太了解,是否容易实现。 实现细节 我有一个JAX-RS端点来处理异步响应,如下所示:
@POST
@Path("/status")
@Consumes("application/xml")
public Response processConfigStatus(@Context UriInfo uriInfo, ConfigStatus configStatus)
{
   // process Status got from the async REST call
   return ResponseHelper.createNoContentResponse();
}

处理和管理的类

Class ProcessData{

  public void updateData()
    checktStatus(uri);
    update();// should wait untill the processConfigStatus() endpoint gives status
  }

  private  checktStatus(String uri){
     // makes a REST call to a URI using a JAX-RS webclient or a httpclient this returns HTTP 200 or 204 code immediatley. And then the Server process the request asynchronously and gives back the status to JAX-RS endpoint(/status).
     post(uri);
  }

}

从另一个类调用方法

ProcessData pd = new ProcessData()
pd.updateData();

您那边也可以提供一些代码 - Bozho
2个回答

4

使用CountDownLatch如何?

这是一种同步辅助工具,允许一个或多个线程等待其他线程执行的一组操作完成。


0
就像您提供的链接中一样,您需要实现一种简单的方式来跟踪有多少异步调用仍在等待响应,并等待该计数为零。

count = numAsyncCalls
..calling all of the RESTful services here (each call must have some sort of callback to decrement 'count' variable above..
while (count > 0)
   wait around

你链接中使用的CountDownLatch看起来与我的伪代码几乎相同


@Bozho,我添加了我计划实现的代码。@jerluc,我还没有在Java中处理回调函数,对于我上面的实现,我们如何处理这个问题?或者从processConfigStatus() REST处理程序中,我可能需要调用ProcessData类中的一个方法来获取状态。 - ravi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接