CompletableScheduledFuture.java

package net.morimekta.testing.concurrent.internal;

import net.morimekta.testing.concurrent.FakeClock;

import java.time.Instant;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Delayed;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

import static java.util.Objects.requireNonNull;
import static java.util.concurrent.TimeUnit.MILLISECONDS;

public class CompletableScheduledFuture<T> extends CompletableFuture<T> implements ScheduledFuture<T> {
    private final FakeClock                clock;
    private final AtomicReference<Instant> nextExecution;

    public CompletableScheduledFuture(FakeClock clock, AtomicReference<Instant> nextExecution) {
        this.clock = requireNonNull(clock, "clock == null");
        this.nextExecution = requireNonNull(nextExecution, "nextExecution == null");
    }

    @Override
    public long getDelay(TimeUnit timeUnit) {
        Instant now = clock.instant();
        Instant next = nextExecution.get();
        if (now.isAfter(next)) {
            return 0L;
        }
        return timeUnit.convert(next.toEpochMilli() - now.toEpochMilli(), MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed delayed) {
        long otherDelay = delayed.getDelay(MILLISECONDS);
        long myDelay = getDelay(MILLISECONDS);
        return Long.compare(myDelay, otherDelay);
    }

    @Override
    @SuppressWarnings("unchecked")
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        CompletableScheduledFuture<Object> that = (CompletableScheduledFuture<Object>) o;
        return isDone() == that.isDone() &&
               isCancelled() == that.isCancelled() &&
               nextExecution.get() == that.nextExecution.get() &&
               Objects.equals(getNow((T) ABSENT), that.getNow(ABSENT));
    }

    @Override
    @SuppressWarnings("unchecked")
    public int hashCode() {
        return Objects.hash(isDone(), isCancelled(), nextExecution.get(), getNow((T) ABSENT));
    }

    private static final Object ABSENT = new Object();
}