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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

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

Trending

  • How You Clear Your HTML5 Canvas Matters
  • How to Keep AI Agents From Going Rogue Using Docker Sandbox
  • MQTT, Kafka, NATS, or Zenoh? Choosing Edge-to-Cloud Messaging by Traffic Pattern
  • Threat Modeling Context-Aware AI: A STRIDE Walkthrough

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
DZone Core CORE ·
Updated Jan. 26, 22 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
27.7K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook