2024-08-01 18:03:21 +08:00
|
|
|
|
package com.jsowell.common.protocol;
|
2024-08-01 15:13:14 +08:00
|
|
|
|
|
|
|
|
|
|
import java.util.concurrent.CountDownLatch;
|
|
|
|
|
|
import java.util.concurrent.TimeUnit;
|
|
|
|
|
|
|
|
|
|
|
|
public class SyncPromise {
|
|
|
|
|
|
|
|
|
|
|
|
// 用于接收结果
|
|
|
|
|
|
// private RpcResponse rpcResponse;
|
|
|
|
|
|
|
|
|
|
|
|
private byte[] rpcResult;
|
|
|
|
|
|
|
|
|
|
|
|
private final CountDownLatch countDownLatch = new CountDownLatch(1);
|
|
|
|
|
|
|
|
|
|
|
|
// 用于判断是否超时
|
|
|
|
|
|
private boolean isTimeout = false;
|
|
|
|
|
|
|
|
|
|
|
|
public boolean isTimeout() {
|
|
|
|
|
|
return isTimeout;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
public byte[] getRpcResult() {
|
|
|
|
|
|
return rpcResult;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
public void setRpcResult(byte[] rpcResult) {
|
|
|
|
|
|
this.rpcResult = rpcResult;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2024-08-26 10:13:02 +08:00
|
|
|
|
public byte[] get(long timeout, TimeUnit unit) throws InterruptedException {
|
2024-08-01 15:13:14 +08:00
|
|
|
|
// 等待阻塞,超时时间内countDownLatch减到0,将提前唤醒,以此作为是否超时判断
|
|
|
|
|
|
boolean earlyWakeUp = countDownLatch.await(timeout, unit);
|
|
|
|
|
|
|
|
|
|
|
|
if(earlyWakeUp) {
|
|
|
|
|
|
// 超时时间内countDownLatch减到0,提前唤醒,说明已有结果
|
|
|
|
|
|
return rpcResult;
|
|
|
|
|
|
} else {
|
|
|
|
|
|
// 超时时间内countDownLatch没有减到0,自动唤醒,说明超时时间内没有等到结果
|
|
|
|
|
|
isTimeout = true;
|
|
|
|
|
|
return null;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
public void wake() {
|
|
|
|
|
|
countDownLatch.countDown();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
}
|