|
25 | 25 | import java.util.concurrent.TimeUnit; |
26 | 26 | import java.util.concurrent.atomic.AtomicLong; |
27 | 27 |
|
| 28 | +import static org.hamcrest.Matchers.greaterThanOrEqualTo; |
| 29 | + |
28 | 30 | public class PrioritizedRunnableTests extends ESTestCase { |
| 31 | + |
| 32 | + // test unit conversion with a controlled clock |
29 | 33 | public void testGetAgeInMillis() throws Exception { |
30 | 34 | AtomicLong time = new AtomicLong(); |
31 | 35 |
|
32 | 36 | PrioritizedRunnable runnable = new PrioritizedRunnable(Priority.NORMAL, time::get) { |
33 | 37 | @Override |
34 | 38 | public void run() { |
35 | | - |
36 | 39 | } |
37 | 40 | }; |
38 | 41 | assertEquals(0, runnable.getAgeInMillis()); |
39 | 42 | int milliseconds = randomIntBetween(1, 256); |
40 | 43 | time.addAndGet(TimeUnit.NANOSECONDS.convert(milliseconds, TimeUnit.MILLISECONDS)); |
41 | 44 | assertEquals(milliseconds, runnable.getAgeInMillis()); |
42 | 45 | } |
| 46 | + |
| 47 | + // test age advances with System#nanoTime |
| 48 | + public void testGetAgeInMillisWithRealClock() throws InterruptedException { |
| 49 | + long nanosecondsInMillisecond = TimeUnit.NANOSECONDS.convert(1, TimeUnit.MILLISECONDS); |
| 50 | + PrioritizedRunnable runnable = new PrioritizedRunnable(Priority.NORMAL) { |
| 51 | + @Override |
| 52 | + public void run() { |
| 53 | + } |
| 54 | + }; |
| 55 | + |
| 56 | + // force at least one millisecond to elapse, but ensure the |
| 57 | + // clock has enough resolution to observe the passage of time |
| 58 | + long start = System.nanoTime(); |
| 59 | + long elapsed; |
| 60 | + while ((elapsed = (System.nanoTime() - start)) < nanosecondsInMillisecond) { |
| 61 | + // busy spin |
| 62 | + } |
| 63 | + |
| 64 | + // creation happened before start, so age will be at least as |
| 65 | + // large as elapsed |
| 66 | + assertThat(runnable.getAgeInMillis(), greaterThanOrEqualTo(TimeUnit.MILLISECONDS.convert(elapsed, TimeUnit.NANOSECONDS))); |
| 67 | + } |
| 68 | + |
43 | 69 | } |
0 commit comments