Search in sources :

Example 1 with TimeoutException

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();
    }
}
Also used : AtomicReference(java.util.concurrent.atomic.AtomicReference) UniSubscription(io.smallrye.mutiny.subscription.UniSubscription) CountDownLatch(java.util.concurrent.CountDownLatch) CompletionException(java.util.concurrent.CompletionException) UniSubscriber(io.smallrye.mutiny.subscription.UniSubscriber) TimeoutException(io.smallrye.mutiny.TimeoutException)

Aggregations

TimeoutException (io.smallrye.mutiny.TimeoutException)1 UniSubscriber (io.smallrye.mutiny.subscription.UniSubscriber)1 UniSubscription (io.smallrye.mutiny.subscription.UniSubscription)1 CompletionException (java.util.concurrent.CompletionException)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1