StackPractices
advanced Por Mathias Paulenko

Guía Completa de Concurrencia en Java

Concurrencia Java en producción: threads, locks, CompletableFuture, virtual threads, executors, colecciones concurrentes, memory model y patrones para apps de alto throughput.

Introducción

El toolkit de concurrencia de Java es el más profundo de cualquier lenguaje mainstream: de synchronized a StampedLock, de ExecutorService a CompletableFuture, de threads de plataforma a virtual threads (JEP 444). Lo difícil no es la API: es elegir la herramienta correcta para cada escenario, porque la elección equivocada falla como siempre fallan los bugs de concurrencia — en silencio, bajo carga, después de publicar.

Esta guía cubre las primitivas y los patrones alrededor: threads, pools, locks, futures, virtual threads, colecciones, atómicos, el memory model, y las decisiones de producción (sizing de pools, evitar deadlocks, pinning) que determinan si tu código sobrevive al tráfico.

flowchart diagram: subgraph Old[

Fundamentos de Threads

Crear Threads

import java.lang.Thread;

// Método 1: Extender Thread
class Worker extends Thread {
    @Override
    public void run() {
        System.out.println("Working in: " + Thread.currentThread().getName());
    }
}
new Worker().start();

// Método 2: Implementar Runnable
Thread thread = new Thread(() -> {
    System.out.println("Working in: " + Thread.currentThread().getName());
});
thread.start();

// Método 3: ExecutorService (recomendado en producción)
import java.util.concurrent.*;

ExecutorService executor = Executors.newFixedThreadPool(8);
executor.submit(() -> {
    System.out.println("Working in: " + Thread.currentThread().getName());
});
executor.shutdown();

Ciclo de Vida del Thread

NEW → RUNNABLE → (BLOCKED / WAITING / TIMED_WAITING) → TERMINATED

NEW: Thread creado, no arrancado
RUNNABLE: Ejecutando o listo para ejecutar
BLOCKED: Esperando un monitor lock
WAITING: Esperando indefinidamente a otro thread
TIMED_WAITING: Esperando una duración concreta
TERMINATED: Thread terminó la ejecución

Propiedades del Thread

Thread thread = new Thread(() -> {
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt(); // Restaurar el flag de interrupción
        return;
    }
});

thread.setName("worker-1");
thread.setPriority(Thread.NORM_PRIORITY); // 1-10, default 5
thread.setDaemon(false); // Los daemon no impiden el cierre de la JVM
thread.start();

// Esperar a que termine
thread.join(5000); // Hasta 5 segundos
System.out.println("Thread alive: " + thread.isAlive());

ExecutorService

Elegir un Thread Pool

import java.util.concurrent.*;

// Pool fijo: uso de recursos predecible
ExecutorService fixed = Executors.newFixedThreadPool(8);

// Pool cacheado: crece bajo demanda, se reduce en idle (60s timeout)
ExecutorService cached = Executors.newCachedThreadPool();

// Un solo thread: ejecución secuencial con cola
ExecutorService single = Executors.newSingleThreadExecutor();

// Programado: tareas diferidas y periódicas
ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(4);
scheduled.scheduleAtFixedRate(() -> heartbeat(), 0, 10, TimeUnit.SECONDS);
scheduled.scheduleWithFixedDelay(() -> cleanup(), 0, 60, TimeUnit.SECONDS);

// Work stealing: paralelismo adaptativo (bueno para ForkJoinTask)
ExecutorService workStealing = Executors.newWorkStealingPool();

Thread Pool Personalizado con ThreadPoolExecutor

import java.util.concurrent.*;

ThreadPoolExecutor executor = new ThreadPoolExecutor(
    4,                          // Core pool size
    16,                         // Max pool size
    60L, TimeUnit.SECONDS,      // Keep-alive para threads idle
    new LinkedBlockingQueue<>(100),  // Cola de trabajo con capacidad
    new ThreadFactory() {
        private int count = 0;
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, "pool-worker-" + count++);
            t.setDaemon(true);
            return t;
        }
    },
    new ThreadPoolExecutor.CallerRunsPolicy()  // Política de rechazo
);

// Políticas de rechazo:
// AbortPolicy: lanza RejectedExecutionException (default)
// CallerRunsPolicy: ejecuta en el thread llamante (backpressure)
// DiscardPolicy: descarta en silencio
// DiscardOldestPolicy: descarta la tarea más vieja en cola

Los detalles que importan: una cola acotada + CallerRunsPolicy es como consigues backpressure natural — cuando el pool se satura, el que envía se frena en vez de la cola crecer hasta matar la JVM. Las fábricas de Executors traen todas colas ilimitadas; para cualquier cosa de cara a usuarios, construye el ThreadPoolExecutor tú mismo.

Apagado Limpio

ExecutorService executor = Executors.newFixedThreadPool(8);

// Enviar tareas
for (int i = 0; i < 100; i++) {
    executor.submit(() -> processItem(i));
}

// Apagado limpio
executor.shutdown(); // Deja de aceptar tareas nuevas
try {
    if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
        executor.shutdownNow(); // Apagado forzado
        if (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
            System.err.println("Pool did not terminate");
        }
    }
} catch (InterruptedException e) {
    executor.shutdownNow();
    Thread.currentThread().interrupt();
}

Locks

synchronized vs ReentrantLock

// synchronized: simple, gestionado por la JVM, sin timeout
public synchronized void incrementSync() {
    count++;
}

// ReentrantLock: flexible, con timeout, puede ser fair
import java.util.concurrent.locks.*;

private final ReentrantLock lock = new ReentrantLock(true); // Lock justo

public void incrementLock() {
    lock.lock();
    try {
        count++;
    } finally {
        lock.unlock(); // DEBE ir en finally
    }
}

// Try con timeout
public boolean tryIncrement(long timeout, TimeUnit unit) {
    try {
        if (lock.tryLock(timeout, unit)) {
            try {
                count++;
                return true;
            } finally {
                lock.unlock();
            }
        }
        return false; // No se pudo adquirir el lock
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        return false;
    }
}

ReadWriteLock

import java.util.concurrent.locks.*;

private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
private final Map<String, String> cache = new HashMap<>();

public String get(String key) {
    rwLock.readLock().lock();
    try {
        return cache.get(key);
    } finally {
        rwLock.readLock().unlock();
    }
}

public void put(String key, String value) {
    rwLock.writeLock().lock();
    try {
        cache.put(key, value);
    } finally {
        rwLock.writeLock().unlock();
    }
}

StampedLock

import java.util.concurrent.locks.*;

private final StampedLock stampedLock = new StampedLock();
private double x, y;

// Lectura optimista: sin lock, validar después
public double distanceFromOrigin() {
    long stamp = stampedLock.tryOptimisticRead();
    double currentX = x, currentY = y;
    if (!stampedLock.validate(stamp)) {
        // Lectura optimista falló, subir a lock de lectura
        stamp = stampedLock.readLock();
        try {
            currentX = x;
            currentY = y;
        } finally {
            stampedLock.unlockRead(stamp);
        }
    }
    return Math.sqrt(currentX * currentX + currentY * currentY);
}

public void move(double deltaX, double deltaY) {
    long stamp = stampedLock.writeLock();
    try {
        x += deltaX;
        y += deltaY;
    } finally {
        stampedLock.unlockWrite(stamp);
    }
}

CompletableFuture

Composición Básica

import java.util.concurrent.*;

CompletableFuture<String> future = CompletableFuture
    .supplyAsync(() -> {
        // Cómputo async
        return fetchUser(123);
    })
    .thenApply(user -> {
        // Transformar resultado
        return user.getName();
    })
    .thenApply(name -> {
        // Encadenar otra transformación
        return name.toUpperCase();
    })
    .thenAccept(name -> {
        // Consumir resultado (sin return)
        System.out.println("Name: " + name);
    })
    .thenRun(() -> {
        // Correr tras la completación
        System.out.println("Done");
    });

future.join(); // Bloquear y obtener resultado

Combinar Múltiples Futures

// Dos futures en paralelo y combinar resultados
CompletableFuture<User> userFuture = CompletableFuture.supplyAsync(() -> fetchUser(123));
CompletableFuture<Orders> ordersFuture = CompletableFuture.supplyAsync(() -> fetchOrders(123));

CompletableFuture<UserProfile> profileFuture = userFuture
    .thenCombine(ordersFuture, (user, orders) -> new UserProfile(user, orders));

// Esperar a que todos terminen
CompletableFuture<Void> all = CompletableFuture.allOf(
    CompletableFuture.supplyAsync(() -> fetchUser(1)),
    CompletableFuture.supplyAsync(() -> fetchUser(2)),
    CompletableFuture.supplyAsync(() -> fetchUser(3))
);
all.join();

// Esperar a cualquiera
CompletableFuture<Object> any = CompletableFuture.anyOf(
    CompletableFuture.supplyAsync(() -> fetchFromPrimary()),
    CompletableFuture.supplyAsync(() -> fetchFromSecondary())
);
Object result = any.join();

Manejo de Errores

CompletableFuture<String> future = CompletableFuture
    .supplyAsync(() -> {
        if (Math.random() > 0.5) {
            throw new RuntimeException("Fetch failed");
        }
        return "success";
    })
    .exceptionally(ex -> {
        // Manejar excepción, devolver fallback
        return "fallback";
    })
    .handle((result, ex) -> {
        // Manejar éxito y excepción
        if (ex != null) {
            return "recovered: " + ex.getMessage();
        }
        return result;
    });

// Patrón retry con CompletableFuture
public CompletableFuture<String> fetchWithRetry(String url, int maxRetries) {
    CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> fetch(url));
    for (int i = 0; i < maxRetries; i++) {
        future = future.exceptionallyCompose(ex -> {
            System.err.println("Retry " + (i + 1) + ": " + ex.getMessage());
            return CompletableFuture.supplyAsync(() -> fetch(url));
        });
    }
    return future;
}

Manejo de Timeouts

import java.util.concurrent.*;

CompletableFuture<String> future = CompletableFuture
    .supplyAsync(() -> slowFetch())
    .orTimeout(5, TimeUnit.SECONDS) // Timeout a los 5s (Java 9+)
    .exceptionally(ex -> {
        if (ex instanceof TimeoutException) {
            return "timeout fallback";
        }
        return "error fallback";
    });

// Completar con valor por defecto tras timeout
CompletableFuture<String> withDefault = CompletableFuture
    .supplyAsync(() -> slowFetch())
    .completeOnTimeout("default", 5, TimeUnit.SECONDS);

Virtual Threads (Java 21+)

Los virtual threads son threads ligeros gestionados por la JVM, no por el SO. Millones de ellos pueden correr sobre unos pocos carrier threads de plataforma.

import java.util.concurrent.*;

// Crear un virtual thread
Thread vt = Thread.ofVirtual().start(() -> {
    System.out.println("Running in virtual thread");
});

// Executor de un virtual thread por tarea
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    List<Future<String>> futures = new ArrayList<>();
    
    for (int i = 0; i < 10_000; i++) {
        final int id = i;
        futures.add(executor.submit(() -> {
            Thread.sleep(Duration.ofSeconds(1)); // ¡La llamada blocking vale!
            return "Result " + id;
        }));
    }
    
    // Las 10.000 tareas terminan en ~1 segundo
    for (Future<String> f : futures) {
        System.out.println(f.get());
    }
}

// Concurrencia estructurada (JEP 525 — finalizada en Java 25)
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
    Subtask<User> user = scope.fork(() -> fetchUser(123));
    Subtask<Orders> orders = scope.fork(() -> fetchOrders(123));
    
    scope.join();           // Esperar a todos
    scope.throwIfFailed();  // Propagar excepción si alguno falló
    
    UserProfile profile = new UserProfile(user.get(), orders.get());
}

Cuándo Usar Virtual Threads

Usa virtual threads cuando:
- Trabajo I/O-bound (llamadas HTTP, queries de bd, I/O de archivos)
- Alto número de tareas concurrentes (miles a millones)
- Quieres estilo blocking-code sin callbacks

NO uses virtual threads cuando:
- Trabajo CPU-bound (usa platform threads o ForkJoinPool)
- Operaciones sensibles a pinning (los bloques synchronized clavan carriers)
- ThreadLocals muy usados (cada virtual thread tiene los suyos)

Dos reglas que los equipos aprenden por las malas: no pooles virtual threads — newVirtualThreadPerTaskExecutor es barato, y poolear derrota el diseño. Y no uses virtual threads para acelerar una tarea lenta: cambian latencia por tarea por throughput, no velocidad. Compara con la concurrencia en Go si estás evaluando el modelo entre lenguajes.

Colecciones Concurrentes

import java.util.concurrent.*;
import java.util.*;

// ConcurrentHashMap: HashMap thread-safe
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("key", 1);
map.computeIfAbsent("key", k -> expensiveCompute(k));
map.merge("counter", 1, Integer::sum); // Incremento atómico

// CopyOnWriteArrayList: List thread-safe, copia al escribir
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
list.add("item"); // Crea una copia nueva

// ConcurrentLinkedQueue: cola no bloqueante
ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<>();
queue.offer("item");
String item = queue.poll();

// BlockingQueue: patrón productor-consumidor
BlockingQueue<String> blockingQueue = new LinkedBlockingQueue<>(100);
blockingQueue.put("item");  // Bloquea si está llena
String item = blockingQueue.take();  // Bloquea si está vacía

// ArrayBlockingQueue: acotada, respaldada por array
BlockingQueue<String> bounded = new ArrayBlockingQueue<>(1000);

// DelayQueue: elementos disponibles tras un delay
class DelayedTask implements Delayed {
    private final long startTime;
    private final String name;
    
    public DelayedTask(String name, long delayMs) {
        this.name = name;
        this.startTime = System.currentTimeMillis() + delayMs;
    }
    
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(startTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }
    
    @Override
    public int compareTo(Delayed o) {
        return Long.compare(startTime, ((DelayedTask) o).startTime);
    }
}

CopyOnWriteArrayList es el que hay que mirar con sospecha: cada mutación copia el array, así que vale para datos de lectura intensiva y escritura rara (listas de listeners, snapshots de config) y mal para todo lo demás.

Variables Atómicas

import java.util.concurrent.atomic.*;

AtomicInteger counter = new AtomicInteger(0);
counter.incrementAndGet();     // ++i
counter.getAndIncrement();     // i++
counter.compareAndSet(0, 1);   // CAS: si es 0, poner 1
counter.updateAndGet(x -> x * 2); // Actualización atómica

AtomicLong longCounter = new AtomicLong(0);
AtomicBoolean flag = new AtomicBoolean(false);
AtomicReference<String> ref = new AtomicReference<>("initial");

// LongAdder: mejor para contadores de alta contención
LongAdder adder = new LongAdder();
adder.increment();
adder.add(10);
long sum = adder.sum(); // No atómico, pero rápido para contar

// LongAccumulator: función de acumulación personalizada
LongAccumulator max = new LongAccumulator(Long::max, Long.MIN_VALUE);
max.accumulate(42);
max.accumulate(17);
long result = max.get(); // 42

Java Memory Model

Relación Happens-Before

// La relación happens-before garantiza visibilidad:
// 1. El thread A escribe en una variable volatile
// 2. El thread B lee la misma volatile
// → Todo lo que A hizo antes de escribir es visible para B

private volatile boolean running = true;

public void stop() {
    running = false; // Escritura volatile — visible a otros threads
}

public void run() {
    while (running) { // Lectura volatile — ve el último valor
        doWork();
    }
}

Publicación Segura

// Inseguro: otro thread podría ver el objeto a medio construir
private SomeObject instance; // NO volatile

// Seguro: volatile garantiza publicación segura
private volatile SomeObject instance;

// Seguro: los campos final son visibles tras la construcción
class ImmutableValue {
    private final int x;
    private final int y;
    
    public ImmutableValue(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

// Seguro: el bloque synchronized establece happens-before
private SomeObject instance;
private final Object lock = new Object();

public SomeObject getInstance() {
    synchronized (lock) {
        if (instance == null) {
            instance = new SomeObject();
        }
        return instance;
    }
}

La regla que cubre casi todo: el estado mutable compartido necesita un borde happens-before (volatile, synchronized, atómicos, o publicación segura vía final). Si no puedes señalar el borde, no lo tienes — y la JVM tiene permitido cachear el valor viejo indefinidamente.

Un caso límite que reaparece en reviews: volatile arregla visibilidad, no atomicidad. counter++ sobre un volatile int sigue siendo leer-modificar-escribir: dos threads pueden incrementar una sola vez entre ambos. volatile es para flags y publicación; para operaciones compuestas quieres AtomicInteger o un lock.

Patrones de Producción

La API es la mitad fácil. Estas son las decisiones que rompen en producción:

Dimensionado de Thread Pools

N_cpu * (1 + W/C) — cores por (1 + ratio espera/cómputo) — es la fórmula de partida, no la respuesta. Mide el W/C real bajo carga: un pool dimensionado para W/C=10 con tareas que en realidad bloquean 100× satura la cola al 10% del throughput esperado. Para un enfoque guiado por SLO, mira la plantilla de dimensionado de thread pools.

Evitar Deadlocks

  • Orden de locks: adquiere locks siempre en un orden global (por identidad o nombre del objeto) — el orden de locks es la única estrategia que mata demostrablemente las esperas cíclicas.
  • tryLock con timeout: te da salida cuando el orden es imposible.
  • jstack / Thread.dumpStack() en staging: reproduce un deadlock una vez y no volverás a publicar locks sin orden. jcmd <pid> Thread.print hace lo mismo en JDKs modernos.

Backpressure

Una cola ilimitada es un memory leak con pasos extra. LinkedBlockingQueue(100) + CallerRunsPolicy convierte “la cola crece hasta el OOM” en “los llamantes se frenan”. Si prefieres descartar a bloquear, AbortPolicy + un circuit breaker arriba es la versión honesta.

Pinning de Virtual Threads

synchronized dentro de un virtual thread lo clava a su carrier — 10.000 virtual threads y 8 carriers clavados a la vez es un bug de inanición de threads disfrazado de modernidad. Cambia synchronized por ReentrantLock en las rutas que tocan virtual threads, o audita la salida de -Djdk.tracePinnedThreads antes del rollout.

Circuit Breaker con CompletableFuture

class CircuitBreaker {
    private final AtomicReference<State> state = new AtomicReference<>(State.CLOSED);
    private final AtomicInteger failureCount = new AtomicInteger(0);
    private final int threshold;
    private final long timeoutMs;
    private volatile long lastFailureTime;

    enum State { CLOSED, OPEN, HALF_OPEN }

    public <T> CompletableFuture<T> execute(java.util.function.Supplier<T> supplier) {
        if (state.get() == State.OPEN) {
            if (System.currentTimeMillis() - lastFailureTime > timeoutMs) {
                state.set(State.HALF_OPEN);
            } else {
                return CompletableFuture.failedFuture(new RuntimeException("Circuit open"));
            }
        }
        return CompletableFuture.supplyAsync(supplier)
            .handle((result, ex) -> {
                if (ex != null) {
                    if (failureCount.incrementAndGet() >= threshold) {
                        state.set(State.OPEN);
                        lastFailureTime = System.currentTimeMillis();
                    }
                    throw new CompletionException(ex);
                }
                failureCount.set(0);
                return CompletableFuture.completedFuture(result);
            }).thenCompose(f -> f);
    }
}

Testing de Código Concurrente

import org.junit.jupiter.api.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;

@Test
void testConcurrentIncrement() throws Exception {
    AtomicInteger counter = new AtomicInteger(0);
    int threads = 100;
    int incrementsPerThread = 1000;
    
    ExecutorService executor = Executors.newFixedThreadPool(threads);
    CountDownLatch latch = new CountDownLatch(threads);
    
    for (int i = 0; i < threads; i++) {
        executor.submit(() -> {
            for (int j = 0; j < incrementsPerThread; j++) {
                counter.incrementAndGet();
            }
            latch.countDown();
        });
    }
    
    latch.await(10, TimeUnit.SECONDS);
    executor.shutdown();
    
    assertEquals(threads * incrementsPerThread, counter.get());
}

@Test
void testCompletableFuture() throws Exception {
    CompletableFuture<String> future = CompletableFuture
        .supplyAsync(() -> "hello")
        .thenApply(String::toUpperCase)
        .thenApply(s -> s + " world");
    
    assertEquals("HELLO world", future.get(5, TimeUnit.SECONDS));
}

Prueba propiedades de concurrencia, no scheduling: invariantes bajo contención (latch + executor, como arriba), semántica de cancelación y timeouts. Un test que verifica orden en un BlockingQueue está probando tu implementación, no una race.

Buenas Prácticas

  • ExecutorService antes que threads a mano. El ciclo de vida del pool es la parte difícil; deja que Executors/ThreadPoolExecutor la posea.
  • Virtual threads para I/O, platform threads para CPU. Empareja el scheduler con la carga, no al revés.
  • ReentrantLock en rutas de virtual threads. synchronized clava carriers.
  • Colas acotadas + CallerRunsPolicy. El backpressure gana al OOM.
  • Restaura los flags de interrupt(). Las interrupciones tragadas rompen la cancelación aguas abajo.

Errores Comunes

  • Poolear virtual threads. newVirtualThreadPerTaskExecutor está pensado para ser barato — poolearlo recupera la restricción que existe para quitar.
  • synchronized en código de muchos virtual threads. El pinning bajo carga es el incidente de producción nº1 con virtual threads.
  • LinkedBlockingQueue ilimitada (default de Executors). La cola crece hasta que la JVM muere.
  • Tragarse InterruptedException. Catch → interrupt() → return; nunca catch-e-ignorar.
  • Atómicos sin borde happens-before. AtomicInteger solo no publica el estado de alrededor — combínalo con volatile/final o sigues teniendo race.

Checklist de Producción

Versiones ejecutables de estos patrones están en el repositorio complementario: executor acotado, circuit breaker y tests de contención.

  • Todos los pools ThreadPoolExecutor con cola acotada + threads con nombre
  • shutdown()/awaitTermination() probado al parar la app
  • synchronized auditado en rutas de virtual threads (pinning)
  • Orden de locks documentado donde coexistan varios locks
  • ThreadLocals revisados antes de activar virtual threads
  • InterruptedException nunca tragado
  • Tests de concurrencia verifican invariantes, no scheduling
  • -Djdk.tracePinnedThreads comprobado en rollout de staging

Ver También

Preguntas frecuentes

¿Debería usar virtual threads o platform threads?

Virtual threads para trabajo I/O-bound con alta concurrencia (miles de llamadas HTTP, queries de bd); platform threads para CPU-bound o control fino del scheduling. Los virtual threads no son más rápidos por tarea — caben más tareas concurrentes en menos threads de SO.

¿Cuál es la diferencia entre thenApply y thenCompose?

thenApply toma una función síncrona y envuelve el resultado; thenCompose toma una función que devuelve un CompletableFuture y lo aplana (como flatMap). Usa thenCompose cuando el siguiente paso es a su vez async.

¿Cómo elijo entre synchronized y ReentrantLock?

synchronized para casos simples (la JVM lo optimiza bien); ReentrantLock cuando necesites tryLock con timeout, fairness, interrumpibilidad o seguridad de pinning con virtual threads. synchronized siempre es reentrante y no tiene timeout.

¿Qué es el pinning de threads en virtual threads?

Los virtual threads se clavan a su carrier dentro de bloques synchronized o métodos nativos — mientras está pinned, el carrier no puede correr otros virtuals. Usa ReentrantLock en rutas calientes con virtual threads.

¿Cómo manejo InterruptedException?

Cápturala, restaura con Thread.currentThread().interrupt(), sal limpiamente — o relánzala. Nunca la tragues; rompe la cancelación cooperativa aguas abajo.

¿Qué es la concurrencia estructurada?

StructuredTaskScope (JEP 525, finalizado en Java 25): las tareas hijas viven dentro de un scope, así que join() espera a todas y throwIfFailed() propaga el primer error — el padre posee el ciclo de vida de los hijos y nada se filtra al fallar.

¿Cuál es el mejor tamaño de thread pool?

N_cpu * (1 + W/C) como punto de partida; mide el ratio espera/cómputo real bajo carga — la fórmula es tan buena como tu estimación de W/C.