### Question:
RetryAfterStaleElement { public void stopAfter(Period period) { boolean again = true; long start = System.currentTimeMillis(); long endMillis = period.getEndMillis(start); FluentExecutionStopped.BecauseOfStaleElement ex = null; while (again && System.currentTimeMillis() < endMillis) { ex = null; try { toRetry(); again = false; } catch (FluentExecutionStopped.BecauseOfStaleElement e) { ex = e; } } if (ex != null) { ex.setDuration(System.currentTimeMillis() - start); throw ex; } }  abstract void toRetry(); void stopAfter(Period period);  }### Answer:
@Test public void works_after_a_couple_of_attempts() { final int tries[] = new int[1]; RetryAfterStaleElement rase = new RetryAfterStaleElement() { @Override public void toRetry() { if (tries[0] < 2) { try { Thread.sleep(500); } catch (InterruptedException e) { } tries[0]++; throw new FluentExecutionStopped.BecauseOfStaleElement("ha", new RuntimeException()); } } }; long start = System.currentTimeMillis(); rase.stopAfter(secs(8)); long elapsed = System.currentTimeMillis() - start; assertThat(elapsed, greaterThan(999L)); assertThat(elapsed, lessThan(1030L)); }
@Test public void keeps_failing_and_therefore_times_out() { RetryAfterStaleElement rase = new RetryAfterStaleElement() { @Override public void toRetry() { throw new FluentExecutionStopped.BecauseOfStaleElement("ha", new RuntimeException()); } }; long start = System.currentTimeMillis(); try { rase.stopAfter(secs(1)); fail("should have barfed"); } catch (FluentExecutionStopped.BecauseOfStaleElement e) { assertThat(e.getMessage().replace("1001", "1000").replace("1002", "1000"), equalTo("ha; 1000 ms duration")); } long elapsed = System.currentTimeMillis() - start; assertTrue(elapsed > 999); assertTrue(elapsed < 1010); }