-
Notifications
You must be signed in to change notification settings - Fork 267
Expand file tree
/
Copy pathDubboCondition.java
More file actions
85 lines (77 loc) · 2.02 KB
/
Copy pathDubboCondition.java
File metadata and controls
85 lines (77 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package com.javaedge.concurrency.condition;
import redis.clients.jedis.Response;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author JavaEdge
* @date 2021/4/21
*/
public class DubboCondition {
Response response;
/**
* 创建锁
*/
private final Lock lock = new ReentrantLock();
/**
* 创建条件变量
*/
private final Condition done = lock.newCondition();
/**
* 调用方通过该方法等待结果
*
* @param timeout
* @return
*/
Object get(int timeout) throws TimeoutException {
long start = System.nanoTime();
// 获取锁
lock.lock();
try {
while (!isDone()) {
// 获取锁后,通过经典的在循环中调用await()方法来实现等待。
done.await(timeout, TimeUnit.SECONDS);
long cur = System.nanoTime();
if (isDone() ||
cur - start > timeout) {
break;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 释放锁
lock.unlock();
}
if (!isDone()) {
throw new TimeoutException();
}
// return returnFromResponse();
return null;
}
/**
* RPC结果是否已经返回
*
* @return
*/
boolean isDone() {
return response != null;
}
// RPC结果返回时调用该方法
private void doReceived(Response res) {
// 获取锁
lock.lock();
try {
response = res;
if (done != null) {
// 通知调用线程,结果已经返回,不用继续等待
done.signal();
}
} finally {
// 释放锁
lock.unlock();
}
}
}