JAVA — CHAPTER 18

Concurrency: Platform Threads to Virtual Threads · Cheat Sheet
Parallel Streams Executor Framework Virtual Threads Synchronization Producer/Consumer
1 SEQUENTIAL vs. PARALLEL STREAMS
// sequential — one core list.stream().map(this::process).toList(); // parallel — splits work across cores list.parallelStream().map(this::process).toList();

When parallel streams help

  • Large datasets + CPU-heavy independent work per element
  • Best with stateless, non-order-dependent operations
  • Overhead can make it slower for small collections
2 PLATFORM THREADS WITH THE EXECUTOR FRAMEWORK
ExecutorService pool = Executors.newFixedThreadPool(4); pool.submit(() -> { doWork(); }); Future<Integer> result = pool.submit(() -> compute()); pool.shutdown();

Why an Executor, not raw Thread?

  • Manages a pool of reusable OS-level ("platform") threads
  • Avoids the cost of creating a new thread for every small task
  • submit() returns a Future to get the result later
3 PROJECT LOOM — VIRTUAL THREADS
try (ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) { for (int i = 0; i < 100_000; i++) { pool.submit(() -> handleRequest()); } }

Platform vs. virtual threads

Platform ThreadVirtual Thread
Managed byOperating SystemJVM (lightweight)
Cost to createRelatively expensiveVery cheap
Typical countHundreds to low thousandsMillions possible
4 STRUCTURED CONCURRENCY & SCOPED VALUES

Structured concurrency

Treats a group of related subtasks running on their own threads as a single unit of work — if one subtask fails, the others are cleanly cancelled together, instead of leaking loose threads.

Scoped values

A modern, safer alternative to ThreadLocal for sharing immutable data down a call chain — automatically cleaned up when the scope ends.

5 THREAD SYNCHRONIZATION OVERVIEW
public synchronized void deposit(double amount) { balance += amount; // only one thread at a time }

The problem it solves

When multiple threads update shared data at once, updates can be lost ("race conditions"). The synchronized keyword (or explicit Lock objects) ensures only one thread executes the critical section at a time.

6 PRODUCER/CONSUMER WITH ArrayBlockingQueue
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10); // Producer thread queue.put(item); // blocks if the queue is full // Consumer thread int item = queue.take(); // blocks if the queue is empty

Why it's useful

A fixed-capacity, thread-safe queue that automatically pauses producers when full and consumers when empty — no manual wait()/notify() needed.

7 MULTITHREADING IN JavaFX

JavaFX UI updates must happen on the JavaFX Application Thread only. For long-running work, run it on a background thread and push UI updates back safely:

new Thread(() -> { var data = loadSlowData(); Platform.runLater(() -> label.setText(data)); }).start();