VOOZH about

URL: https://dzone.com/articles/creating-thread-pool-in-java-or-how-to-reuse-threa

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


Related

  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 Updated Jan. 26, 22 · Tutorial
Likes
Comment
Save
27.0K 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 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.

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:

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:

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:

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

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

Let's be friends: