Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 77 ยท Java Interview Questions

Java: Concurrency, Streams and Modern Java

Prepare Java interview answers on synchronized, executors, CompletableFuture, lazy streams, virtual threads and sealed types, with runnable stand-ins.

The last Java lesson in this track covers the questions that separate "knows the syntax" from "has written real services": how threads share data safely, how thread pools work, how asynchronous results are combined, how streams evaluate, and what modern Java (virtual threads, sealed types, pattern matching) changed.

The Java code in this lesson is read-only, because the real JVM scheduler is not available in this page. Every idea also has a stand-in written in Node.js that runs on the site. The stand-ins model the behavior (races, pools, lazy pipelines, exhaustive matching); they are not Java. For the full tutorials see Synchronization, Executors, CompletableFuture, Streams, Virtual Threads and Sealed Classes. The previous lesson is JVM, Memory Model and Garbage Collection.

Race conditions and synchronized

Q: What is a race condition, and how does synchronized fix it? A race condition happens when the result depends on how threads interleave. The classic case is count++: it is three steps (read, add, write), so two threads can both read 5 and both write 6, losing an update. synchronized gives mutual exclusion (only one thread holds a given object's monitor at a time) and also visibility (changes made inside the block are visible to the next thread that acquires the same monitor).

Java
class Counter {
    private int count;

    public synchronized void increment() { count++; }   // locks on "this"
    public synchronized int get() { return count; }     // reads must lock too
}

What a lock gives you

Exclusion One thread in the block at a time.
Visibility Writes are seen by the next lock holder.
Ordering Code is not reordered across the lock.

Both the writer and the reader must use the same lock.

1 / 2

Follow-up: synchronized versus volatile? volatile gives visibility and ordering for a single variable but no atomicity for compound actions like count++. Use AtomicInteger for a lock-free counter, synchronized or a Lock when several variables must change together.

Follow-up: what is a deadlock? Two threads each hold a lock the other needs. The standard cure is to always acquire locks in one global order. Operating Systems: Processes, Threads and Deadlocks covers the four conditions.

Node.js is single-threaded, but await creates the same interleaving problem for any read-modify-write. The stand-in below loses updates without a lock and keeps them with a tiny promise-based mutex:

Node.js Stand-in: a lost update and a mutex

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The real part: Java's monitor exclusion. The stand-in part: the cooperative await interleaving and the promise-chain mutex.

Executors and thread pools

Q: Why use an ExecutorService instead of new Thread()? Creating a platform thread is expensive (an OS thread with its own stack), and unbounded creation can exhaust memory. A pool reuses a fixed set of worker threads, queues extra tasks, and gives you Future results, shutdown control and a single place to tune.

Java
ExecutorService pool = Executors.newFixedThreadPool(4);
Future<Integer> answer = pool.submit(() -> expensiveCalculation());
System.out.println(answer.get());   // blocks until done
pool.shutdown();                    // stop accepting work, finish queued tasks

Q: How should you size a pool? For CPU-bound work, about the number of cores. For blocking I/O, more, because threads spend most of their time waiting. Prefer a ThreadPoolExecutor with a bounded queue and an explicit rejection policy in production: the Executors factory methods hide an unbounded queue (newFixedThreadPool) or an unbounded thread count (newCachedThreadPool).

Pitfalls: forgetting shutdown() keeps the JVM alive; Future.get() without a timeout can hang; exceptions thrown inside submit() tasks are captured in the Future and vanish if you never call get().

The stand-in pool below accepts many tasks but never runs more than two at once:

Node.js Stand-in: a fixed-size pool with a queue

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

CompletableFuture

Q: What does CompletableFuture add over Future? A plain Future can only be blocked on. CompletableFuture is composable and non-blocking: you attach steps that run when the result arrives.

Java
CompletableFuture<String> page =
    CompletableFuture.supplyAsync(() -> loadUser(42))              // runs on a pool
        .thenApply(user -> user.name())                            // map the value
        .thenCompose(name -> CompletableFuture.supplyAsync(        // flat-map: next async step
            () -> loadGreeting(name)))
        .exceptionally(error -> "fallback");                       // recover from any failure

CompletableFuture<Void> both =
    CompletableFuture.allOf(page, otherFuture);                    // wait for several

Know the vocabulary: thenApply transforms a value (like map), thenCompose chains another future (like flatMap), thenCombine joins two independent futures, allOf and anyOf wait for several, and exceptionally or handle deal with errors. Without an explicit executor, supplyAsync uses the common ForkJoinPool, which is a poor place for blocking calls: pass your own executor for I/O.

Promises are the closest JavaScript relative, so the stand-in maps the same shapes:

Node.js Stand-in: thenApply, thenCompose and exceptionally

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Streams

Q: What is a stream, and is it a data structure? No. A stream is a one-shot pipeline over a source. It does not store elements. Intermediate operations (filter, map, sorted) are lazy: nothing runs until a terminal operation (collect, forEach, count, findFirst) pulls elements through. Elements flow one at a time through the whole chain, which is why findFirst can stop early.

Java
List<String> names = people.stream()
    .filter(p -> p.age() >= 18)
    .map(Person::name)
    .sorted()
    .toList();                       // terminal: Java 16+, returns an unmodifiable list

Stream<String> s = names.stream();
s.count();
s.count();                           // IllegalStateException: stream has already been operated upon or closed

Q: When is parallelStream() a good idea? Rarely by default. It splits work across the common ForkJoinPool, so it only pays off for large, CPU-heavy, stateless operations on easily split sources (arrays, ArrayList). It hurts with small data, blocking calls, shared mutable state or LinkedList. Measure first.

Common follow-ups: map versus flatMap (one-to-one versus one-to-many flattened), reduce versus collect (immutable fold versus mutable accumulation), and why side effects in map or filter are a smell.

JavaScript generators are lazy too, so they show the same element-at-a-time order:

Node.js Stand-in: a lazy pipeline and early exit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Virtual threads

Q: What are virtual threads, and what problem do they solve? Since Java 21, a virtual thread is a lightweight thread managed by the JVM, not the OS. When it blocks on I/O, the JVM unmounts it from its carrier (platform) thread so that carrier can run another virtual thread. You can have millions of them, which makes the simple "one thread per request" style scale again without reactive code.

Java
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    for (int i = 0; i < 10_000; i++) {
        executor.submit(() -> {
            Thread.sleep(Duration.ofSeconds(1));   // blocking is cheap here
            return fetchFromRemoteService();
        });
    }
}   // close() waits for all tasks

Guidance interviewers like: do not pool virtual threads (create one per task), keep them for blocking I/O (CPU-bound work gains nothing), and be careful with ThreadLocal and long-held monitors. Older JDKs "pinned" the carrier thread while a virtual thread was inside synchronized; recent JDKs (24 and later) removed most of that pinning.

The stand-in starts 10,000 cheap tasks that each wait, mimicking blocking calls:

Node.js Stand-in: ten thousand cheap waiting tasks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Sealed types, records and pattern matching

Q: What are sealed classes for? A sealed type lists exactly which classes may extend it (permits). The compiler therefore knows every subtype, so a switch over the type can be exhaustive with no default, and adding a new subtype turns every incomplete switch into a compile error. Combined with records and pattern matching (final since Java 21), this gives clean algebraic data types.

Java
sealed interface Shape permits Circle, Rectangle, Square {}
record Circle(double radius) implements Shape {}
record Rectangle(double width, double height) implements Shape {}
record Square(double side) implements Shape {}

static double area(Shape shape) {
    return switch (shape) {                       // no default needed
        case Circle c -> Math.PI * c.radius() * c.radius();
        case Rectangle(double w, double h) -> w * h;   // record pattern
        case Square s -> s.side() * s.side();
    };
}

Permitted subclasses must be final, sealed or non-sealed. Other modern features worth naming: var, text blocks, instanceof patterns, and switch expressions.

JavaScript has no sealed types, but a tagged union with a throwing default imitates the "unknown variant is a bug" idea:

Node.js Stand-in: an exhaustive match over tagged shapes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is count++ on a shared int not thread-safe?

    The increment is a compound action. Interleaved threads can both read the same value and both write the same result, losing one update.
  2. 2. What does an intermediate stream operation like filter do when it is called?

    Intermediate operations are lazy. Elements are pulled through the pipeline one at a time by the terminal operation.
  3. 3. Which advice about virtual threads is correct?

    Virtual threads are cheap, so you do not pool them. They help when many tasks wait on I/O; they do not add CPU capacity.
  4. 4. What benefit do sealed types give a switch?

    Because the permitted subtypes are known, a switch covering all of them is complete, and a newly added subtype produces a compile error in incomplete switches.

Summary

  • Races come from compound read-modify-write steps; synchronized, locks and atomics provide exclusion and visibility, and locks must be taken in a consistent order.
  • Pools reuse threads and queue work; size them by workload, bound the queue and always shut down.
  • CompletableFuture composes asynchronous steps with thenApply, thenCompose, allOf and exceptionally.
  • Streams are lazy, single-use pipelines; use parallelStream() only after measuring.
  • Virtual threads make blocking-style code scale: one per task, no pooling.
  • Sealed types with records and pattern matching give exhaustive, compiler-checked switch expressions.

Next: C and C++: Pointers, Memory and Undefined Behavior.