TimeBasedKeys { public long nextKey() { final long timestamp = System.currentTimeMillis(); final int increment = counterFor(timestamp); if (increment <= maximumCounterValue) { return (timestamp << counterBits) + increment; } return this.nextKey(); } protected  TimeBasedKeys( short bitsUsedInCounter ); static TimeBasedKeys create(); static TimeBasedKeys create( int bitsUsedInCounter ); long nextKey(); long getCounterStartingAt( long millisInUtc ); long getCounterEndingAt( long millisInUtc ); long getCounterEndingAfter( long millisInUtc ); long getTimeGenerated( long key ); static final short DEFAULT_BITS_IN_COUNTER; }
@Test public void shouldObtain10MillionCountersThreadSafe() { print(counter.nextKey()); for (int i = 0; i != 10000000; ++i) { counter.nextKey(); } print(counter.nextKey()); }
@Test public void shouldObtain10MillionCountersFromThreadSafeUsingMultipleThreads() { print(counter.nextKey()); for (int j = 0; j != 100; ++j) { new Thread(new Runnable() { @Override public void run() { for (int i = 0; i != 100000; ++i) { counter.nextKey(); } } }).run(); } print(counter.nextKey()); }