Java 21 Certification Guide - Part 7
Virtual Threads and Concurrency
Welcome to the seventh article in my series on preparing for the Java 21 certification.
Over the next several posts, we’ll walk through the most important language changes, APIs, and tricky details you’ll need to know for the exam.
In this article, we’ll focus on Threads. These concepts aren’t something most developers use in their daily work, so they can feel a bit tricky.
To make things practical, we’ll analyze a question in the style of the certification exam.
❓ Question
What is the output from this code?
private static volatile int counter = 0;
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();
for (int i = 0; i < 100; i++) {
executor.submit(() -> increment());
}
executor.shutdown();
executor.awaitTermination(1, TimeUnit.SECONDS);
System.out.println("Final counter = " + counter);
}
private static void increment() {
counter++;
}A) Final counter = 100
B) Final counter = 0
C) Final counter = A number between 1 and 100
D) Compilation error: volatile cannot be used with int
E) Final counter = unpredictable, but always at least 50
🔎 Explanation
volatileensures visibility, not atomicityEach thread sees the updated value of
counter,but
counter++is not atomic (it is read → increment → write).So multiple threads can overwrite each other’s increments.
Using virtual threads
Executors.newVirtualThreadPerTaskExecutor()creates lightweight threads.Behavior regarding race conditions is the same as with platform threads.
Why not always 100?
Because increments may collide.
Example: Two threads read
counter = 5simultaneously → both write6. One increment is lost.
Why not 0?
At least some tasks will execute before termination.
Very unlikely to remain 0, unless executor shut down immediately (not the case here).
So the result is nondeterministic
Anywhere between 1 and 100, depending on thread scheduling and race conditions.
✅ Correct Answer
C
👉 This is the seventh article in the next articles of this series, and the last one. If you enjoyed this series of Java 21 Certification articles, don’t forget to hit the Like 👍 button below, it really helps support more content like this!


