CountDownLatch
理解:有一个任务想要往下执行,但必须要等到其他的任务执行完毕后才可以继续往下执行。
假如我们这个想要继续往下执行的任务调用一个CountDownLatch对象的await()方法,其他的任务执行完自己的任务后调用同一个CountDownLatch对象上的countDown()方法,这个调用await()方法的任务将一直阻塞等待,直到这个CountDownLatch对象的计数值减到0为止。
DpFuture dpFuture = new DpFuture();
channel.pipeline().context(dprClientHandler.getClass()).attr(DpAttributeKey.attributeKey).set(dpFuture);
channel.writeAndFlush(req).sync();
dpResponse = dpFuture.get(TIMEOUT);
public class DpFuture {
private final CountDownLatch latch = new CountDownLatch(1);
private volatile DPResponse dprResponse;
public DPResponse get(long timeout) throws Exception {
if(!latch.await(timeout,TimeUnit.SECONDS)){
throw new TimeoutException();
}
return dprResponse;
}
public void setDone(DPResponse dprResponse) {
this.dprResponse = dprResponse;
latch.countDown();
}
}
public class DprClientHandler extends SimpleChannelInboundHandler<DPResponse> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, DPResponse msg) throws Exception {
Attribute<DpFuture> attr = ctx.attr(DpAttributeKey.attributeKey);
DpFuture dpFuture=attr.get();
dpFuture.setDone(msg);
}
}