Home  >  Article  >  Java  >  Java Thread Pool

Java Thread Pool

PHPz
PHPzOriginal
2024-08-30 16:03:21950browse

A thread pool, like the name, suggests is a collection of threads that can be reused. These threads have been created previously and can also function with offering solution to overheads when there is already a collection of threads available; these can be reused and resolve the issue of thread cycles and waiting for threads to complete their task. As the thread will already be existing whenever the request arrives, it will remove the process of thread creation and, as a result, save that time and make the processing faster. In this topic, we are going to learn about Java Thread Pool.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Working of Java Thread Pool

All threads in thread pools implement the methods from java.util.concurrent. There is a thread pool that is managed by the Java thread pool. The easiest way of seeing this pool is the more threads you make use of, the less time each thread will spend upon doing the actual work. It is a way that helps in saving resources in an application where multi-threading can be used. There is a queue that is maintained by this Java thread for pools.

The worker threads keep waiting for tasks to be assigned and get them executed. To create a thread pool, ThreadPoolExecutor is used in Java. The collection of runnable threads are responsible for managing the threads in the Java Thread pool. After this, the worker threads come in picture and form queues. The thread pool monitors these queues.

The java.util.concurrent.Executors help us with the factory and support methods that are needed for managing the threads. This class is also responsible for creating the thread pool. Now your next question might be, what is this Executor? Executor provides different classes which are a part of the utility class.

The technical working of thread pool can be thought of like a pool where you have your concurrent code, which is split into tasks that can run in parallel. Then they are submitted for execution to the pool. There are task submitters, Executor Services, task queues, and in the end, the thread pool. The pattern can help you in controlling the number of threads that are present in the application. It decides its lifecycle, schedules the tasks, and keeps the tasks incoming in the work queue.

The Executorshelper class has various methods that have pre-configured thread pool instances. The Executor and ExecutorService interfaces help in working with different implementation in the pool. The code must be in the decoupled format before the actual implementation. There is another interface that is used. It is a ThreadPoolExecutor. It is an extensible thread pool implementation where many parameters can be specified, and it will result in fine-tuning. The parameters which can be used include core pool size, maximum pool size, and keepalive time. The queue can grow only up to the maximum pool size.

Example of Java Thread Pool

Let us create a pool and see how it works.

Code:

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
// The Job class will be executed in this case
class Job implements Runnable
{
private String name;
public Job(String s)
{
name = s;
}
// The task name will be populated first for the ones which were not running already, and the thread will sleep for 2s
//This entire method will be repeated 6 times
public void run()
{
try
{
for (int i = 0; i<=5; i++)
{
if (i==0)
{
Date d = new Date();
System.out.println("We are in "
+ " task name - "+ name);
//prints the task name every time the new task is started
}
else
{
System.out.println("The job "+
name +" is already running ");
// prints the job name which is already running
}
Thread.sleep(2000); // The thread is in sleep mode for 2 secs
}
System.out.println(name+" job is completes");
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
public class Test
{
// Here we define the maximum threads we have
static final int MAX_Threads= 5;
public static void main(String[] args)
{
Runnable run1 = new Job("task 1");
Runnable run2 = new Job("task 2");
Runnable run3 = new Job("task 3");
//A new thread pool is created with maximum number of threads
ExecutorService newpool = Executors.newFixedThreadPool(MAX_Threads);
newpool.execute(run1);
newpool.execute(run2);
newpool.execute(run3);
newpool.shutdown();
}
}

The above code covers each step of the creation of the thread till it’s shutdown. There is a maximum thread limit fixed and created. Once this is done, there are three jobs created which execute one by one. There is also a sleep time allotted for 2 secs for each job. As the thread pool is created and all jobs work simultaneously, we can see that this entire process will run 6 times. When the if statement runs in the thread pool, it checks if the job is already running or not. If the job has not started running, it will execute the if block. If it is already running, then the else block will be run. It will display the job name and say that it is already running. The thread pool is created, and then all 3 jobs are run. Once the jobs are run, we shut down the thread pool that we have created.

Below will be the output of the given program.

Output:

Java Thread Pool

It runs until all tasks are completed.

Advantages and Disadvantages of Thread Pools

We have several advantages of Thread Pool in Java. To name a few, below are the main advantages:

  • It results in better and efficient performance of the CPU and program.
  • As different threads are working all processes, it saves time.
  • The main advantage of the thread pool is the reuse of threads that are already present. There is no need of creating new threads again and again.
  • It provides real-time access, which helps in working with real-time data.

We also have some disadvantages of the thread pool, though. Below are the disadvantages:

  • You cannot set the priority of tasks, and also, these cannot be tracked.
  • When used more, these can be deleted automatically.

Conclusion

As a result, thread pools are an efficient way of handling the multiple tasks which we have at our hand. Java provides us with the facility of reusing the threads and making use of the existing resources.

The above is the detailed content of Java Thread Pool. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Daemon Thread in JavaNext article:Daemon Thread in Java