Fix test that assumed the absence of thread context switch between calls.

This commit is contained in:
Andrzej Bialecki 2018-05-21 12:12:14 +02:00
parent 4603541d18
commit 7c8fdcd1b6
2 changed files with 32 additions and 8 deletions

View File

@ -51,6 +51,12 @@ public abstract class TimeSource {
return getTimeNs();
}
@Override
long[] getTimeAndEpochNs() {
long time = getTimeNs();
return new long[] {time, time};
}
@Override
public void sleep(long ms) throws InterruptedException {
Thread.sleep(ms);
@ -87,6 +93,12 @@ public abstract class TimeSource {
return epochStart + getTimeNs() - nanoStart;
}
@Override
long[] getTimeAndEpochNs() {
long time = getTimeNs();
return new long[] {time, epochStart + time - nanoStart};
}
@Override
public void sleep(long ms) throws InterruptedException {
Thread.sleep(ms);
@ -125,6 +137,12 @@ public abstract class TimeSource {
return epochStart + getTimeNs() - nanoStart;
}
@Override
long[] getTimeAndEpochNs() {
long time = getTimeNs();
return new long[] {time, epochStart + time - nanoStart};
}
@Override
public void sleep(long ms) throws InterruptedException {
ms = Math.round((double)ms / multiplier);
@ -198,6 +216,9 @@ public abstract class TimeSource {
*/
public abstract long getEpochTimeNs();
// for unit testing
abstract long[] getTimeAndEpochNs();
/**
* Sleep according to this source's notion of time. Eg. accelerated time source such as
* {@link SimTimeSource} will sleep proportionally shorter, according to its multiplier.

View File

@ -33,8 +33,13 @@ public class TestTimeSource extends SolrTestCaseJ4 {
}
private void doTestEpochTime(TimeSource ts) throws Exception {
long prevTime = ts.getTimeNs();
long prevEpochTime = ts.getEpochTimeNs();
// XXX the method below doesn't work reliably because
// XXX there could be a long thread context switch between these two calls:
// long prevTime = ts.getTimeNs();
// long prevEpochTime = ts.getEpochTimeNs();
long[] prevTimeAndEpoch = ts.getTimeAndEpochNs();
long delta = 500000000; // 500 ms
long maxDiff = 200000;
if (ts instanceof TimeSource.SimTimeSource) {
@ -42,14 +47,12 @@ public class TestTimeSource extends SolrTestCaseJ4 {
}
for (int i = 0; i < 10; i++) {
ts.sleep(500);
long curTime = ts.getTimeNs();
long curEpochTime = ts.getEpochTimeNs();
long diff = prevTime + delta - curTime;
long[] curTimeAndEpoch = ts.getTimeAndEpochNs();
long diff = prevTimeAndEpoch[0] + delta - curTimeAndEpoch[0];
assertTrue(ts + " time diff=" + diff, diff < maxDiff);
diff = prevEpochTime + delta - curEpochTime;
diff = prevTimeAndEpoch[1] + delta - curTimeAndEpoch[1];
assertTrue(ts + " epochTime diff=" + diff, diff < maxDiff);
prevTime = curTime;
prevEpochTime = curEpochTime;
prevTimeAndEpoch = curTimeAndEpoch;
}
}
}