use of io.smallrye.mutiny.TimeoutException in project smallrye-mutiny by smallrye.
the class UniBlockingAwait method await.
public static <T> T await(Uni<T> upstream, Duration duration, Context context) {
nonNull(upstream, "upstream");
validate(duration);
if (!Infrastructure.canCallerThreadBeBlocked()) {
throw new IllegalStateException("The current thread cannot be blocked: " + Thread.currentThread().getName());
}
CountDownLatch latch = new CountDownLatch(1);
AtomicReference<T> reference = new AtomicReference<>();
AtomicReference<Throwable> referenceToFailure = new AtomicReference<>();
UniSubscriber<T> subscriber = new UniSubscriber<T>() {
@Override
public Context context() {
return (context != null) ? context : Context.empty();
}
@Override
public void onSubscribe(UniSubscription subscription) {
// Do nothing.
}
@Override
public void onItem(T item) {
reference.set(item);
latch.countDown();
}
@Override
public void onFailure(Throwable failure) {
referenceToFailure.compareAndSet(null, failure);
latch.countDown();
}
};
AbstractUni.subscribe(upstream, subscriber);
try {
if (duration != null) {
if (!latch.await(duration.toMillis(), TimeUnit.MILLISECONDS)) {
referenceToFailure.compareAndSet(null, new TimeoutException());
}
} else {
latch.await();
}
} catch (InterruptedException e) {
referenceToFailure.compareAndSet(null, e);
Thread.currentThread().interrupt();
}
Throwable throwable = referenceToFailure.get();
if (throwable != null) {
if (throwable instanceof RuntimeException) {
throw (RuntimeException) throwable;
}
throw new CompletionException(throwable);
} else {
return reference.get();
}
}
Aggregations