Last active
August 29, 2015 14:16
-
-
Save pidster/656e12c4c6dd9152b3aa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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