如何等待线程直到响应可用

问题描述

我们有以下场景,我们有一个具有两个方法并在多个线程之间共享的类。

public class Response {
  Map <String,APIResponse> requestIdToResponse = new ConcurrentHashMap();

  public void sendResponse(ApiRequest apirequest) {
      String requestId = apiRequest.getRequestId();
      // Send async call to invoke the rest API. and populate the hashmap with results.
  }

  // This should be sync call. Once the async call finish
  //  concurrent hashmap should be populated with request id and response
  public ApiResponse getAPiResponse(String requestId) {

     // How to make a current thread wait for certain timeout lets say(15 min) until the response 
     // is available in the concurrent hashmap for given request id.
 
  }

}

解决方法

你可以使用 CountDownLatch

public class Response {
  Map <String,APIResponse> requestIdToResponse = new ConcurrentHashMap();
  CountDownLatch countDownLatch = new CountDownLatch(1);

  public void sendResponse(ApiRequest apirequest) {
      APIResponse result= apiRequest.getRequestId();
      requestIdToResponse.put(requestId,result);
      countDownLatch.countDown();
  }

  public ApiResponse getAPiResponse(String requestId) {
       countDownLatch.await();
       requestIdToResponse.get(requestId);
  }


   //send request thread example
     new Thread (()->{
              
                result =  sendResponse(request);
                 requestIdToResponse.put(requestid,result);
              
            }).start();

      //you can get result after request thread finished
         getAPiResponse(requestId);  

}