English:
You're absolutely right in your intuition: threads in a thread pool are not supposed to die after running one Runnable
. The whole point of a thread pool is to reuse threads, avoiding the overhead of frequent thread creation and destruction.
Code:You're absolutely right in your intuition: threads in a thread pool are not supposed to die after running one Runnable. The whole point of a thread pool is to reuse threads, avoiding the overhead of frequent thread creation and destruction.
Code
public void run(){
while(!isStopped()){
try{
Runnable runnable = (Runnable) taskQueue.dequeue();
runnable.run();
} catch(Exception e){
// log or otherwise report exception,
// but keep pool thread alive.
}
}
}
…is actually doing exactly what a thread pool worker thread should do. The while (!isStopped()) loop ensures that the thread:
Waits for tasks from the queue,
Executes them, and
Loops back to wait again, rather than terminating.
This loop enables the thread to stay alive, sleeping (or blocking) when no tasks are available, and waking up when a new one arrives. It doesn't die after runnable.run() – it continues waiting for the next task.
So no, the thread is not garbage collected after a single task unless the pool is being shut down or the thread terminates due to a fatal exception. Instead, it's parked (blocked) on the task queue, consuming little to no CPU.
Spanish:
Tu intuición es completamente acertada: los hilos dentro de un thread pool no mueren después de ejecutar un solo Runnable
. Justamente, el propósito de un pool de hilos es reutilizar los mismos hilos para múltiples tareas, reduciendo así el costo de rendimiento asociado a crear y destruir hilos frecuentemente.
Codigo:
public void run(){
while(!isStopped()){
try{
Runnable runnable = (Runnable) taskQueue.dequeue();
runnable.run();
} catch(Exception e){
// log o manejar la excepción,
// pero mantener el hilo del pool vivo.
}
}
}
…en realidad representa correctamente el comportamiento de un hilo trabajador (worker) en un thread pool. La condición while (!isStopped())
asegura que el hilo:
Espera por tareas desde una cola,
Las ejecuta, y
Vuelve a esperar, en lugar de finalizar.
🔁 Este bucle permite que el hilo siga vivo, esperando (bloqueado) cuando no hay tareas, y despertando automáticamente cuando se encola una nueva. No se destruye ni se recolecta por el GC después de cada tarea.
Dicho de otra forma: el hilo entra en estado inactivo (bloqueado, sin consumir CPU) y se reutiliza cuando llega la siguiente tarea. Solo muere cuando el pool se cierra (shutdown()), o en casos de errores fatales no controlados.