Skip to content

Instantly share code, notes, and snippets.

@pidster
Last active August 29, 2015 14:16
Show Gist options
  • Select an option

  • Save pidster/656e12c4c6dd9152b3aa to your computer and use it in GitHub Desktop.

Select an option

Save pidster/656e12c4c6dd9152b3aa to your computer and use it in GitHub Desktop.

Revisions

  1. pidster renamed this gist Mar 3, 2015. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. pidster created this gist Mar 3, 2015.
    34 changes: 34 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    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());
    }
    }