Java SDK并发包通过Lock
和Condition
两个接口来实现管程,其中Lock
用于解决互斥问题,Condition
用于解决同步问题。
Lock
相较于内置加锁机制synchronized
,显示锁Lock
除了支持类似synchronized
隐式加锁的方法外,还支持超时、非阻塞、可中断的方式获取锁,这三种方式为我们编写更加安全、健壮的并发程序提供了很大的便利。
UML
Condition
UML
使用示例
RPC请求(Dubbo源码)
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
| private final Lock lock = new ReentrantLock(); private final Condition done = lock.newCondition();
Object get(int timeout){ long start = System.nanoTime(); lock.lock(); try { while (!isDone()) { done.await(timeout); long cur=System.nanoTime(); if (isDone() || cur-start > timeout){ break; } } } finally { lock.unlock(); } if (!isDone()) { throw new TimeoutException(); } return returnFromResponse(); }
boolean isDone() { return response != null; }
private void doReceived(Response res) { lock.lock(); try { response = res; if (done != null) { done.signal(); } } finally { lock.unlock(); } }
|