我有一个底层的异步无序查询/响应系统,我想同步。查询和响应可以通过用唯一ID标记查询来映射,这些ID随后将伴随相应的响应。使异步查询同步
我试图使它同步使用两个ConcurrentHashMap
s:一个从ID映射到结果,一个从相同ID映射到CountDownLatch
es。
public Result execute(Query query) throws InterruptedException {
int id = atomicInteger.incrementAndGet();
CountDownLatch latch = new CountDownLatch(1);
latchMap.put(id, latch);
query.executeAsyncWithId(id); // Probably returns before result is ready
try {
latch.await(); // Blocks until result is ready
return resultMap.remove(id);
} catch (InterruptedException e) {
latchMap.remove(id); // We are not waiting anymore
throw e;
}
}
以及处理传入的结果代码:执行查询时,代码是这样
public void handleResult(Result result) {
int id = result.getId();
CountDownLatch latch = latchMap.remove(id);
if (latch == null) {
return; // Nobody wants result
}
resultMap.put(id, result);
latch.countDown();
}
这种方法是从一个线程读取从底层系统的所有传入的结果称为(只有一个这样的阅读器线程)。
首先,我不确定线程安全性,但似乎没有必要为此使用两个HashMap
(特别是因为ID从不重复使用)。任何改进想法?
因此,删除使用“闩锁”的代码,但不应在此函数内定义。我没有看到任何会使这种异步的东西。 – 2010-07-31 21:07:30
它是实际执行异步查询的底层系统。我已经将该方法重命名为“executeAsyncWithId”来澄清。 – hakos 2010-07-31 21:14:31
嘿,我建议你发布自己的答案作为答案,并接受! – 2010-08-01 07:01:32