Enterprise Java

Calculations in Quarkus Qute using AtomicInteger

Quarkus’ Qute Templating Engine is very handy for creating server-side rendered pages. Besides the regular loops and control structures, there’s also a possibility to set and update variables, at least with a small trick. In the following, we’ll see how to do some arithmetic calculations using Java’s AtomicInteger.

Usually, you can invoke methods of objects that are passed to Qute, but you can’t easily update the variables itself. There’s the {#let} directive to define variables but in order to update values we need to use types that provide methods to do so, unlike Java primitives.

Imagine we’d like to have multiple nested loops and would like some global counter:

{#let counter=math:atomicInt(1)}
{#for entry in entries}
    <li>{counter.getAndIncrement()}. {entry_count}.
        {entry.title} {#if entry_hasNext}OR{/}</li>

{#for i in 5}
    <li>{counter.getAndIncrement()}. {i_count}.
        Entry number {i}{#if i_hasNext},{/}</li>

What happens is that the counter variable is of type AtomicInteger and the getAndIncrement method returns and changes the internal numeric value. We provide the instance via a template extension method:

@TemplateExtension(namespace = "math")
static AtomicInteger atomicInt(int initial) {
    return new AtomicInteger(initial);

The result looks like follows:

  • 1. 1. This is an entry OR
  • 2. 2. This is another entry OR
  • 3. 3. This is yet another entry
  • 4. 1. Entry number 1,
  • 5. 2. Entry number 2,
  • 6. 3. Entry number 3,
  • 7. 4. Entry number 4,
  • 8. 5. Entry number 5

As an alternative, you can also initialize and provide the AtomicInteger in your Java code:

// ... in your Qute REST controller
return template.data("entries", entries, "counter", new AtomicInteger(1));

Then you can get rid of the {#let} directive:

{#for entry in entries}
    <li>{counter.getAndIncrement()}. {entry_count}.
        {entry.title} {#if entry_hasNext}OR{/}</li>

{#for i in 5}
    <li>{counter.getAndIncrement()}. {i_count}.
        Entry number {i}{#if i_hasNext},{/}</li>

These examples are using Quarkus version 2.7.0.Final.

Published on Java Code Geeks with permission by Sebastian Daschner, partner at our JCG program. See the original article here: Calculations in Quarkus Qute using AtomicInteger

Opinions expressed by Java Code Geeks contributors are their own.

Sebastian Daschner

Sebastian Daschner is a self-employed Java consultant and trainer. He is the author of the book 'Architecting Modern Java EE Applications'. Sebastian is a Java Champion, Oracle Developer Champion and JavaOne Rockstar.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button