Async with CountDown latches?

68 views
Skip to first unread message

Jaikiran Pai

unread,
Apr 6, 2021, 4:22:02 AM4/6/21
to Quarkus Development mailing list
While working on this PR https://github.com/quarkusio/quarkus/pull/16253
I noticed an interesting programming style. Now with a lot of the code
being async (reactive?), I'm seeing code like the one in VertxRecorder
where you have some async construct which you trigger from the main
thread and since the async construct uses callbacks, you then use a
CountDownLatch which counts down in the callbacks and the main thread
waits on the latch. Something like:

consumer.completionHandler(new Handler<AsyncResult<Void>>() {

                    @Override
                    public void handle(AsyncResult<Void> ar) {
                        latch.countDown();
                        if (ar.failed()) {
registrationFailures.add(ar.cause());
                        }
                    }
                });
                messageConsumers.add(consumer);
            }
            try {
                latch.await();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new IllegalStateException("Unable to register all
message consumer methods", e);
            }
            if (!registrationFailures.isEmpty()) {
                // just log/raise the first failure
                throw new RuntimeException("Registration of one or more
message consumers failed", registrationFailures.get(0));
            }


Turns out this isn't the only place where we have similar latches
(there's VertxCoreRecorder which has a similar code and perhaps more).
In reality, all this code really wants is a blocking behaviour - block
till the actions are "done".

I don't have experience with reactive/async programming, but constructs
like this perhaps should have better APIs? Imagine something like
Thread.join() semantics. That would prevent all these usages of latches
in the caller code, plus the potential bugs these usages can introduce
(like the one that PR tries to fix).


-Jaikiran


clement escoffier

unread,
Apr 6, 2021, 4:37:27 AM4/6/21
to Jaikiran Pai, Quarkus Development mailing list
Hello,

It's because it uses the "bare" Vert.x API which is inherently non-blocking and asynchronous. So yes, when you want to block, you end up having to play with latches. The Mutiny variant has "blocking" methods. 

Clement

--
You received this message because you are subscribed to the Google Groups "Quarkus Development mailing list" group.
To unsubscribe from this group and stop receiving emails from it, send an email to quarkus-dev...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/quarkus-dev/9d428e82-ee36-5649-b8c1-56409807b08c%40gmail.com.
Reply all
Reply to author
Forward
0 new messages