com.taobao.drc.clusterclient.util.SettableFuture Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of consumer-core Show documentation
Show all versions of consumer-core Show documentation
The java consumer core component for Data Transmission Service
package com.taobao.drc.clusterclient.util;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author yangyang
* @since 2017/8/7
*/
public class SettableFuture implements Future {
private final Lock lock = new ReentrantLock();
private final Condition finished = lock.newCondition();
private V value;
private Throwable throwable;
private boolean done = false;
public void success(V value) {
lock.lock();
try {
if (isDone()) {
throw new IllegalStateException("The future has already been fulfilled");
}
this.value = value;
this.done = true;
finished.signalAll();
} finally {
lock.unlock();
}
}
public void failure(Throwable throwable) {
lock.lock();
try {
if (isDone()) {
throw new IllegalStateException("The future has already been fulfilled");
}
if (throwable != null) {
this.throwable = throwable;
} else {
this.throwable = new IllegalArgumentException("Future was fulfilled with a null failure");
}
this.done = true;
finished.signalAll();
} finally {
lock.unlock();
}
if (throwable == null) {
throw new NullPointerException();
}
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public boolean isDone() {
lock.lock();
try {
return done;
} finally {
lock.unlock();
}
}
@Override
public V get() throws InterruptedException, ExecutionException {
lock.lock();
try {
while (!done) {
finished.await();
}
if (throwable != null) {
throw new ExecutionException(throwable);
}
return value;
} finally {
lock.unlock();
}
}
@Override
public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
long remainingNs = TimeUnit.NANOSECONDS.convert(timeout, unit);
long dueNs = System.nanoTime() + remainingNs;
lock.lock();
try {
while (!done) {
if (remainingNs < 0) {
throw new TimeoutException();
}
finished.await(remainingNs, TimeUnit.NANOSECONDS);
remainingNs = dueNs - System.nanoTime();
}
if (throwable != null) {
throw new ExecutionException(throwable);
}
return value;
} finally {
lock.unlock();
}
}
}