簡體   English   中英

等待異步調用先完成然后在Java中進行

[英]Waiting for an asynchronous call to complete first and then proceed in Java

我遇到的情況是,我調用一個方法,該方法又會在進一步進行之前觸發異步HTTP REST調用(稍后將狀態發送到另一個端點)。 我希望該方法等待,直到我將響應返回到端點,檢查我得到的狀態,然后繼續進行。 我正在尋找Java中可行的解決方案。 任何偽代碼或實現都將有所幫助

看到了類似的案例@ 輕量級的等待一組異步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();

如何使用CountDownLatch呢?

一種同步幫助,它允許一個或多個線程等待,直到在其他線程中執行的一組操作完成為止。

就像在您提供的鏈接中一樣,您將必須實現一種方法來簡單地跟蹤有多少異步調用仍在等待響應,並一直等到該計數為零。


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看起來與我的偽代碼幾乎相同

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM