I have a basic out-of-order asynchronous request / response system that I want to make synchronous. Requests and responses can be displayed by marking requests with unique identifiers, which, in turn, will accompany the corresponding responses.
My attempt to do this synchronously uses two ConcurrentHashMaps: one that displays from identifiers to results, and one that displays the same identifiers for CountDownLatch. When executing the request, the code is as follows:
public Result execute(Query query) throws InterruptedException {
int id = atomicInteger.incrementAndGet();
CountDownLatch latch = new CountDownLatch(1);
latchMap.put(id, latch);
query.executeAsyncWithId(id);
try {
latch.await();
return resultMap.remove(id);
} catch (InterruptedException e) {
latchMap.remove(id);
throw e;
}
}
And the code for processing the incoming result:
public void handleResult(Result result) {
int id = result.getId();
CountDownLatch latch = latchMap.remove(id);
if (latch == null) {
return;
}
resultMap.put(id, result);
latch.countDown();
}
This method is called from a stream that reads all incoming results from the base system (there is only one such read stream).
, , HashMap ( , ). ?