DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Java Virtual Threads and Scaling
  • Virtual Threads: A Game-Changer for Concurrency
  • Deep Dive Into Java Executor Framework
  • Java Thread Dump Analysis

Trending

  • A Developer's Guide to Mastering Agentic AI: From Theory to Practice
  • How to Convert XLS to XLSX in Java
  • Measuring the Impact of AI on Software Engineering Productivity
  • AI's Dilemma: When to Retrain and When to Unlearn?
  1. DZone
  2. Coding
  3. Java
  4. Learn How to Create Thread Pool in Java and How to Reuse Thread

Learn How to Create Thread Pool in Java and How to Reuse Thread

Learn about the thread pool and how to create it in Java from scratch. This post includes an intro, implementation, and testing of a simple thread pool version.

By 
Dmitry Egorov user avatar
Dmitry Egorov
DZone Core CORE ·
Updated Jan. 26, 22 · Tutorial
Likes (15)
Comment
Save
Tweet
Share
25.8K Views

Join the DZone community and get the full member experience.

Join For Free

Creating and Running Thread

Thread creation is a well-known process and there are two ways to create it:

  • Extend Thread and override the run method
  • Feed Runnable to Thread constructor

Let's implement both options:

 
 public static void main(String[] args) throws Exception {
    // Thread from runnable
    Thread thread = new Thread(() -> System.out.println("hey from runnable"));
    // Thead from extened thread class
    Thread myThread = new MyThread();
}

static class MyThread extends Thread {
    @Override
    public void run() {
    System.out.println("hey from thread extended class");
    }
}


Difference Between Start and Run Methods

Each thread provides two methods that start their activity but there is one significant difference:

  • The run method executes the instruction in the currently running thread.
  • Start method executes the instruction in a new separate thread.

Let's portray both cases:

Thread Methods: Start and Run


Thread Pool: Reusing Existing Thread To Save Memory

Thread Pool Pattern stands for reusing existing threads and running all new instructions without allocation of new threads. The thread pool controls the number of running threads and is widely used in production.

Thread Pool Pattern

This pattern has implementations in Java:

  • Executors.newScheduledThreadPool(THREAD_POOL_NUMBER)
  • Executors.newCachedThreadPool()

Here, we won't investigate existent Java thread pools, but try to create our own. 

Thread’s Runnable Cannot Be Changed

Existent Thread design does not allow you to change instructions (content in Runnable). Therefore, all available setters are:

Existent Thread Design

There is no setRunnable among provided setters. Then how does Java's Thread Pool work?

You Can Run Another Runnable Inside Current Thread

Java allows running other runnables right inside the current thread. Therefore, to dynamically "change" runnables we can run runnables inside one thread's loop. Let's create only one worker (thread) that will execute other runnables (tasks) inside the infinity loop:

Creating Worker (Thread) to Execute Other Runnables (Tasks)

Thread Execute Runnable Inside Without Calling New Thread

As you can see in the previous code, when the Main Thread gets newTaskBeExecuted, it uses run() method instead of the start() one. Doing this doesn't call a new Thread, but executes it right inside. To double-check that no other threads are used we print the current thread name and confirm that there is only one single thread used.

Using Created Thread Pool

Now having our own Thread Pool, we can feed our task (Runnables). Once the main worker (the only one single thread) became available, it will run:

Worker (Thread Pool) Executing Other Runnables (Tasks)

After execution, we can see that different runnables have been executed inside one single Main Worker thread. This proves that our thread pool is working as we expected.  

Conclusion

In this article, we reviewed the core idea of the Thread Pool pattern and implemented an oversimplified version. Our example won't fit into production, but it explains how the real Thread Pool works. Here you can copy used examples. 

Thanks for reading, and your comments are welcome!

Thread pool Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Java Virtual Threads and Scaling
  • Virtual Threads: A Game-Changer for Concurrency
  • Deep Dive Into Java Executor Framework
  • Java Thread Dump Analysis

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!