Java/J2EE and SOA (348 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (16 Blogs)
  • Comprehensive Java Course (4 Blogs)
  • Java/J2EE and SOA (345 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

What is a Java Thread Pool and why is it used?

Last updated on Jun 19,2023 5.6K Views

39 / 72 Blog from Java Core Concepts

Whenever you are building a server application, the demand for creating a new thread arises every time a request arrives. This new request is the new thread that is created. This tutorial would be circulating around the thread pool in Java, depicting its advantages and disadvantages followed by the definition!

The topics discussed in this article are:

Let’s begin!

What is the Thread Pool in Java?

As the name suggests, the thread pool in Java is actually a pool of Threads. In a simple sense, it contains a group of worker threads that are waiting for the job to be granted. They are reused in the whole process.

In a Thread Pool, a group of fixed size threads is created. Whenever a task has to be granted, one of the threads is pulled out and assigned that task by the service provider, as soon as the job is completed the thread is returned back to the thread pool. Thread pool is preferably used because active threads consume system resources, when is JVM creates too many threads at the same time, the system could run out of memory. Hence the number of threads to be created has to be limited. Therefore the concept of the thread pool is preferred!

Let us move towards our next segment which states the risks related to the thread pool in Java.

Risk in the Java Thread Pool

There are a few risks while you are dealing with the thread pool, like;

  • Thread Leakage: If a thread is removed from the pool to perform a task but not returned back to it when the task is completed, thread leakage occurs.
  • Deadlock: In thread pool is executing thread is waiting for the output from the block the thread waiting in the queue due to unavailability of thread for execution, there’s a case of a deadlock.
  • Resource Thrashing: More number of threads than the optimal number required can cause starvation problems leading to resource thrashing.

Now, let us move towards the advantages of the thread pool.

Advantages of a Thread Pool

Some of the advantages of using thread pool when programming in Java are:

  • Better performance
  • Saves time
  • No need to create a thread again and again
  • Easy to access
  • Real-time usage

Now, let us check out the disadvantages of the thread pool.

Disadvantages of the Thread Pool

Some of the disadvantages of using thread pool when programming are:

  • There is no control over the priority and state of the thread you are working with.
  • There is no stable identity given to the thread, no track can be kept.
  • When there is a high demand for the thread pool, the process may be deleted.
  • The thread pool can not work well when two threads are working in parallel.
  • There are several situations where the application code can be affected by another application code, despite robust application isolation.

Now let me introduce to the implementation part of the thread pool. Here it goes!

Implementation of a Thread Pool

Check out the code below to understand the concept of thread pool in Java

Code: 

package MyPackage;
 
import java.util.concurrent.LinkedBlockingQueue;
 
public class ThreadPool {
private final int nThreads;
private final PoolWorker[] threads;
private final LinkedBlockingQueue<Runnable> queue;
 
public ThreadPool(int Threads) {
this.nThreads = Threads;
queue = new LinkedBlockingQueue<Runnable>();
threads = new PoolWorker[Threads];
 
for (int i = 0; i < nThreads; i++) {
threads[i] = new PoolWorker();
threads[i].start();
}
}
 
public void execute(Runnable task) {
synchronized (queue) {
queue.add(task);
queue.notify();
}
}
 
private class PoolWorker extends Thread {
public void run() {
Runnable task;
 
while (true) {
synchronized (queue) {
while (queue.isEmpty()) {
try {
queue.wait();
} catch (InterruptedException e) {
System.out.println("An error occurred while queue is waiting: " + e.getMessage());
}
}
task = (Runnable)queue.poll();
}
 
// If we don't catch RuntimeException,
// the pool could leak threads
try {
task.run();
} catch (RuntimeException e) {
System.out.println("Thread pool is interrupted due to an issue: " + e.getMessage());
}
}
}
}
}

This brings us to the end of this ‘Thread Pool in Java’ article. I have covered one of the most fundamental and important topics of Java. I hope you are clear with all that has been shared with you in this article.

Make sure you practice as much as possible and revert your experience.  

Check out the Java Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. We are here to help you with every step on your journey, for becoming a besides this java interview questions, we come up with a curriculum which is designed for students and professionals who want to be a Java Developer. 

Stay up-to-date with the latest Flutter features and best practices through our Flutter Course.

Got a question for us? Please mention it in the comments section of this ‘Thread Pool in Java’ article and we will get back to you as soon as possible.

Upcoming Batches For Java Certification Training Course
Course NameDateDetails
Java Certification Training Course

Class Starts on 27th April,2024

27th April

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

What is a Java Thread Pool and why is it used?

edureka.co