[test] awaitBusy: add a ceiling to max sleep time

When using `awaitBusy`, sometimes, you might not want to double time between two runs in an infinitive manner.

For example, let's say it will probably take 30 seconds to run a test.
When doubling all the time, you will most likely wait for a bigger time than needed:

|iteration|ms           |s            |duration (ms)|duration (s)|
|-----------|-------------|-----------|-----------|-----------|
|1|1|0,001|1|0,001|
|2|2|0,002|3|0,003|
|3|4|0,004|7|0,007|
|4|8|0,008|15|0,015|
|5|16|0,016|31|0,031|
|6|32|0,032|63|0,063|
|7|64|0,064|127|0,127|
|8|128|0,128|255|0,255|
|9|256|0,256|511|0,511|
|10|512|0,512|1023|1,023|
|11|1024|1,024|2047|2,047|
|12|2048|2,048|4095|4,095|
|13|4096|4,096|8191|8,191|
|14|8192|8,192|16383|16,383|
|15|16384|16,384|32767|32,767|
|16|32768|32,768|65535|65,535|
|17|65536|65,536|131071|131,071|
|18|131072|131,072|262143|262,143|
|19|262144|262,144|524287|524,287|
|20|524288|524,288|1048575|1048,575|
|21|1048576|1048,576|2097151|2097,151|

For example here, if the task is successful after 35 seconds, we will most likely have to wait for 32s more before the Predicate is run again.

With this patch, the maximum sleep time is now set to 1 second.
This commit is contained in:
David Pilato 2015-07-04 23:08:32 +02:00
parent 1d7fc6b4f2
commit af1dc6d809
1 changed files with 6 additions and 4 deletions

View File

@ -435,18 +435,20 @@ public abstract class ElasticsearchTestCase extends LuceneTestCase {
return awaitBusy(breakPredicate, 10, TimeUnit.SECONDS);
}
// After 1s, we stop growing the sleep interval exponentially and just sleep 1s until maxWaitTime
private static final long AWAIT_BUSY_THRESHOLD = 1000L;
public static boolean awaitBusy(Predicate<?> breakPredicate, long maxWaitTime, TimeUnit unit) throws InterruptedException {
long maxTimeInMillis = TimeUnit.MILLISECONDS.convert(maxWaitTime, unit);
long iterations = Math.max(Math.round(Math.log10(maxTimeInMillis) / Math.log10(2)), 1);
long timeInMillis = 1;
long sum = 0;
for (int i = 0; i < iterations; i++) {
while (sum + timeInMillis < maxTimeInMillis) {
if (breakPredicate.apply(null)) {
return true;
}
sum += timeInMillis;
Thread.sleep(timeInMillis);
timeInMillis *= 2;
sum += timeInMillis;
timeInMillis = Math.min(AWAIT_BUSY_THRESHOLD, timeInMillis * 2);
}
timeInMillis = maxTimeInMillis - sum;
Thread.sleep(Math.max(timeInMillis, 0));