Search code examples
javaquarkusreactiveimperative

Quarkus reactive vs quarkus imperative does it matter?


Hello I was reading the following article Quarkus reactive architecture

At the start of the article it says

Quarkus is reactive. It’s even more than this: Quarkus unifies reactive and imperative programming. You don’t even have to choose: you can implement reactive components and imperative components then combine them inside the very same application.

just below the middle the article mentions

Thanks to hints in your code (such as the @Blocking and @NonBlocking annotations), Quarkus extensions can decide when the application logic is blocking or non-blocking.

My questions is does it matter if i write reactive or imperative? For example

Reactive approach

    @GET
    public Uni<List<Fruit>> get() {
        return sf.withTransaction((s,t) -> s
                .createNamedQuery("Fruits.findAll", Fruit.class)
                .getResultList()
        );
    }

Imperative approach

    @GET
    @NonBlocking
    public List<Fruit> get() {
        return entityManager.createNamedQuery("Fruits.findAll", Fruit.class)
                .getResultList();
    }

Will both these code snippets run with the same reactive benefits?


Solution

  • Assuming your second snippet uses classic blocking Hibernate ORM, it will not work just like the first snippet (which seemingly uses Hibernate Reactive). It contains a blocking call, so you will block the event loop, which is the worst thing you can do in a non-blocking architecture, as it basically works against all the benefits that a non-blocking architecture can give you (see https://vertx.io/docs/vertx-core/java/#golden_rule).

    If your methods are blocking, which includes calls to other libraries that are blocking, you must not pretend that they are @NonBlocking. If you remove the @NonBlocking annotation, the method call will be offloaded to a thread pool and the event loop stays free to handle other requests. This has some overhead, plus the thread pool is not infinite, but I dare to say that it will work just fine in a vast majority of cases.