MinuteBucketIdProvider implements BucketIdProvider { @Override public BucketId get() { long nanosSinceInitial = ticker.read() - initialValue; int id = (int) (nanosSinceInitial / ONE_MINUTE_IN_NANOS); long nanosSinceBoundary = nanosSinceInitial % ONE_MINUTE_IN_NANOS; long timeAtBoundary = TimeUnit.MILLISECONDS.toNanos(currentTimeMillis()) - nanosSinceBoundary; return bucketId(id, timeAtBoundary); } @Inject  MinuteBucketIdProvider();  MinuteBucketIdProvider(Ticker ticker); @Override BucketId get(); long getLastSystemTimeMillis();  }
@Test public void testInitialState() { long startTime = getCurrentTimeNanos(); BucketId bucketId = new MinuteBucketIdProvider(ticker).get(); assertEquals(bucketId.getId(), 0); assertGreaterThanOrEqual(bucketId.getTimestamp(), startTime); assertLessThanOrEqual(bucketId.getTimestamp(), getCurrentTimeNanos()); ticker.elapseTime(27, TimeUnit.HOURS); ticker.elapseTime(977_777, TimeUnit.NANOSECONDS); startTime = getCurrentTimeNanos(); bucketId = new MinuteBucketIdProvider(ticker).get(); assertEquals(bucketId.getId(), 0); assertGreaterThanOrEqual(bucketId.getTimestamp(), startTime); assertLessThanOrEqual(bucketId.getTimestamp(), getCurrentTimeNanos()); }
@Test public void testMinuteBoundary() { ticker.elapseTime(27, TimeUnit.HOURS); ticker.elapseTime(977_777, TimeUnit.NANOSECONDS); long startTime = getCurrentTimeNanos(); BucketIdProvider idProvider = new MinuteBucketIdProvider(ticker); BucketId bucketId = idProvider.get(); assertEquals(bucketId.getId(), 0, "initial state"); assertGreaterThanOrEqual(bucketId.getTimestamp(), startTime); assertLessThanOrEqual(bucketId.getTimestamp(), getCurrentTimeNanos()); ticker.elapseTime(59_999_999_999L, TimeUnit.NANOSECONDS); startTime = getCurrentTimeNanos(); bucketId = idProvider.get(); assertEquals(bucketId.getId(), 0, "before minute boundary"); assertGreaterThanOrEqual(bucketId.getTimestamp(), startTime - 59_999_999_999L); assertLessThanOrEqual(bucketId.getTimestamp(), getCurrentTimeNanos() - 59_999_999_999L); ticker.elapseTime(1, TimeUnit.NANOSECONDS); startTime = getCurrentTimeNanos(); bucketId = idProvider.get(); assertEquals(bucketId.getId(), 1, "on minute boundary"); assertGreaterThanOrEqual(bucketId.getTimestamp(), startTime); assertLessThanOrEqual(bucketId.getTimestamp(), getCurrentTimeNanos()); }