例子中:
conditionfactory类所在包路径:
conditionfactory类是一个condition工厂,with()会新建一个conditionfactory实例:
conditionfactory带参构造函数如下:
构造函数的参数值:
通过这些参数可知,默认的超时时间为10s, 轮询间隔为100ms;
通过conditionfactory的成员方法,对成员变量进行替换,比如atmost(60, seconds):
将final成员变量this.timeoutconstraint替换成用户设置的new duration(60, seconds);
<code>and()</code>返回this;
当用户再设置<code>pollinterval(one_hundred_milliseconds)</code>时:
会重新new一个对象,one_hundred_milliseconds会赋给final成员变量:pollinterval,之前赋过的值保留,比如:timeoutconstraint还是上一步设置的new duration(60, seconds);依次类推new duration(50, milliseconds)赋给final成员变量:polldelay; "count is greater 6"赋给final成员变量:alias。
最终实例化的conditionfactory对象中,成员变量为:
contiditionfactory类成员方法until():
generateconditionsettings()将conditionfactory的final变量赋值给javabean对象conditionsettings:
实例化callablecondition类,构造函数:
同时实例化conditionawaiter对象,conditionawaiter构造函数:
并调用callablecondition实例的await()方法:
接着调用conditionawaiter实例的await():
conditionawaiter类中有个countdownlatch成员变量:
实例化时,定义了:
countdownlatch:
在conditionawaiter实例的await()方法中,创建了一个轮询线程:
其中while循环中:
<code>future<?> future = executor.submit(new conditionpoller(pollinterval));</code>
线程执行体:
具体执行:conditionevaluationresult result = conditionevaluator.eval(delayed);
实例化conditionawaiter时传入conditionevaluator的实现类conditionevaluationwrapper;
conditionevaluationwrapper中eval()方法:
其中:
<code>boolean conditionfulfilled = matcher.call();</code>
call()返回computed result。
matcher实例在conditionevaluationwrapper构造函数中实例化:
本例为:
如果异步执行结果满足,latch.countdown();
使latch.getcount() == 0,导致while循环break中断;
否则,异步执行结果不满足,每次while循环sleep:
while循环每次将eval()提交给线程池;如果是duration.forever一直等待执行结束;否则,最多等待maxtimeout查看执行结果。
创建轮询线程后,判断latch是否为0,如果不为0,线程阻塞;
最后根据finishedbeforetimeout为false,拼接提示语。
错误提示语:
定义countdownlatch变量latch,并初始化为<code>new countdownlatch(1)</code>;
启动一个轮询线程,该轮询线程执行体中实现了while循环,每次先判断latch.getcount()是否为0,如果为0,跳出while循环;否则,将判断异步结果是否成功的任务提交给线程池executor执行,执行体会判断是否成功,成功则latch.countdown()(导致latch.getcount()为0,下次跳出while循环);同时,每次while循环执行 <code>thread.sleep(pollinterval.getvalueinms());</code> 如果轮询线程执行体while循环一直不满足条件,主线程将阻塞maxtimeoutunit:<code>latch.await(maxtimeout, maxtimeoutunit)</code>, 如果latch.getcount()不为0,即异步校验不成功,finishedbeforetimeout置为false, <code>finishedbeforetimeout = latch.await(maxtimeout, maxtimeoutunit)</code>, 输出异常信息。