Better-Whitelist/src/main/java/io/gitlab/jfronny/betterwhitelist/server/ManualFuture.java

67 lines
1.7 KiB
Java

package io.gitlab.jfronny.betterwhitelist.server;
import org.jetbrains.annotations.NotNull;
import java.util.concurrent.*;
public class ManualFuture<T> implements Future<T> {
private Result state = Result.RUNNING;
private T result;
@Override
public boolean cancel(boolean b) {
if (state != Result.RUNNING) return false;
cancel();
return true;
}
@Override
public boolean isCancelled() {
return state == Result.CANCELLED;
}
@Override
public boolean isDone() {
return state == Result.DONE;
}
@Override
public T get() throws InterruptedException, ExecutionException {
while (state == Result.RUNNING) Thread.sleep(10);
if (state == Result.CANCELLED) throw new CancellationException();
return result;
}
@Override
public T get(long l, @NotNull TimeUnit timeUnit) throws TimeoutException {
long millis = timeUnit.toMillis(l) / 10;
while (state == Result.RUNNING && millis-- > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException ignored) {
}
}
if (millis <= 0) throw new TimeoutException();
if (state == Result.CANCELLED) throw new CancellationException();
return result;
}
public void cancel() {
this.state = Result.CANCELLED;
}
public void complete(T result) {
if (state != Result.RUNNING) throw new IllegalStateException("Attempted to complete non-running future");
this.state = Result.DONE;
this.result = result;
}
public void reset() {
this.state = Result.RUNNING;
}
private enum Result {
RUNNING, CANCELLED, DONE
}
}