【问题标题】:How to wait on thread until the response is available如何等待线程直到响应可用
【发布时间】:2021-09-30 07:09:06
【问题描述】:

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

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.
 
  }

}

【问题讨论】:

  • 你的意思是一个线程调用getAPiResponse,应该等待另一个线程调用sendResponse

标签: java concurrency java.util.concurrent java-threads


【解决方案1】:

你可以使用 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);  

}

【讨论】:

  • 您好,我使用了带条件机制的锁。在 getAPIresponse 方法中,我需要等到响应在并发哈希映射中可用。
  • await方法正在等待,直到ConcurrentHashMap获取值可用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多