CompletableScheduledFuture.java
/*
* Copyright (c) 2020, Stein Eldar Johnsen
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
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;
@SuppressWarnings("PreferJavaTimeOverload")
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 instanceof CompletableScheduledFuture)) {
return false;
}
CompletableScheduledFuture<Object> that = (CompletableScheduledFuture<Object>) o;
return isDone() == that.isDone() &&
isCancelled() == that.isCancelled() &&
Objects.equals(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();
}