Skip to content

Instantly share code, notes, and snippets.

@pidster
Last active August 29, 2015 14:16
Show Gist options
  • Save pidster/656e12c4c6dd9152b3aa to your computer and use it in GitHub Desktop.
Save pidster/656e12c4c6dd9152b3aa to your computer and use it in GitHub Desktop.
public class AtomicLongThreadedTimeSupplier implements Supplier<Instant> {
private static final AtomicLong counter = new AtomicLong();
private final AtomicLong epochMilli = new AtomicLong();
private final long timeout;
public AtomicLongThreadedTimeSupplier() {
this(1000L);
}
public AtomicLongThreadedTimeSupplier(long timeout) {
this.timeout = timeout;
String threadName = String.format("time-supplier-%s", counter.incrementAndGet());
Thread thread = new Thread(this::reset, threadName);
thread.setDaemon(true);
thread.start();
}
private void reset() {
try {
epochMilli.set(System.currentTimeMillis());
TimeUnit.MICROSECONDS.sleep(timeout);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public Instant get() {
return Instant.ofEpochMilli(epochMilli.get());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment