I am trying to understand multi-threading in Java. I have written the following java program to test thread pool.
public class ThreadPoolTest
{
public static void main(String[] args)
{
ExecutorService executorService = Executors.newFixedThreadPool(5);
for( int i = 0; i < 3; i++ )
{
executorService.submit(new Task(i+1));
}
executorService.shutdown();
}
public static class Task implements Runnable
{
private int taskId;
public Task(int id)
{
taskId = id;
}
@Override
public void run() {
System.out.println("Executing task " + taskId + " performed by " + Thread.currentThread().getName() );
try
{
Thread.sleep(3000);
}
catch(InterruptedException interruptEx)
{
System.out.println(Thread.currentThread().getName() + " got interrupted ");
}
System.out.println("Finished executing task " + taskId );
}
}
}
The main thread creates executor which creates 5 threads and I have submitted only 3 tasks. After that I am shutting down the executor. When I run the code, the main thread finishes before the child threads. In this case, does JVM takes care of the child threads? Also I have created a thread pool with 5 threads, but submitted only 3 tasks. Will the remaining 2 threads are terminated when the main thread exits?
What actually happens when the executor service is shutdown?
Once a thread in the thread pool completes its task, it's returned to a queue of waiting threads. From this moment it can be reused. This reuse enables applications to avoid the cost of creating a new thread for each task. There is only one thread pool per process.
Since active threads consume system resources, a JVM creating too many threads at the same time can cause the system to run out of memory. This necessitates the need to limit the number of threads being created. What is ThreadPool in Java?
Java Thread pool represents a group of worker threads that are waiting for the job and reused many times. In the case of a thread pool, a group of fixed-size threads is created. A thread from the thread pool is pulled out and assigned a job by the service provider.
Thread is dead itself after its run method returns. It might still be in the heap, but it will not have its own stack anymore, and not do anything.
From the doc of ExecutorService#shutdown()
:
Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.
This means that all the Jobs you submitted to the Executor will finish on their own time without interrupting or "hurrying" them, and the executor will finish up the worker threads properly, but neither will the service accept new Jobs, nor will it terminate instantly.
Compare ExecutorService#shutdownNow()
, which will try to terminate as quickly as possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With