Executors newCachedThreadPool Method Example

Introduction

The newCachedThreadPool method in the Executors class creates a thread pool that creates new threads as needed but will reuse previously constructed threads when they are available. This type of thread pool is suitable for applications that launch many short-lived tasks.

Table of Contents

  1. Overview of newCachedThreadPool Method
  2. Creating a Cached Thread Pool
  3. Submitting Tasks to Cached Thread Pool
  4. Example: Using newCachedThreadPool
  5. Shutting Down the Thread Pool
  6. Conclusion

1. Overview of newCachedThreadPool Method

The newCachedThreadPool method creates a thread pool that can dynamically adjust the number of threads in the pool based on the workload. If no threads are available for reuse, a new thread is created. Threads that remain idle for 60 seconds are terminated and removed from the pool.

Syntax:

public static ExecutorService newCachedThreadPool()

2. Creating a Cached Thread Pool

To create a cached thread pool, use the newCachedThreadPool method.

Example:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CachedThreadPoolExample {
    public static void main(String[] args) {
        // Creating a cached thread pool
        ExecutorService executorService = Executors.newCachedThreadPool();

        // Your tasks go here

        executorService.shutdown();
    }
}

3. Submitting Tasks to Cached Thread Pool

Tasks can be submitted to the cached thread pool using the submit or execute method.

Example:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CachedThreadPoolTaskExample {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();

        // Submit tasks to the executor service
        for (int i = 1; i <= 5; i++) {
            final int taskId = i;
            executorService.submit(() -> {
                System.out.println("Task " + taskId + " executed by " + Thread.currentThread().getName());
            });
        }

        executorService.shutdown();
    }
}

Output:

Task 1 executed by pool-1-thread-1
Task 2 executed by pool-1-thread-2
Task 3 executed by pool-1-thread-3
Task 4 executed by pool-1-thread-4
Task 5 executed by pool-1-thread-5

4. Example: Using newCachedThreadPool

Let's create a complete example that demonstrates how to create a cached thread pool, submit tasks, and shut it down.

Example:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class Task implements Runnable {
    private final String name;

    public Task(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        System.out.println("Task " + name + " is being executed by " + Thread.currentThread().getName());
        try {
            Thread.sleep(2000); // Simulate long-running task
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class CachedThreadPoolDemo {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();

        for (int i = 1; i <= 5; i++) {
            Task task = new Task("Task " + i);
            executorService.submit(task);
        }

        executorService.shutdown();

        try {
            if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
                executorService.shutdownNow();
            }
        } catch (InterruptedException e) {
            executorService.shutdownNow();
        }

        System.out.println("All tasks are finished.");
    }
}

Output:

Task Task 1 is being executed by pool-1-thread-1
Task Task 2 is being executed by pool-1-thread-2
Task Task 3 is being executed by pool-1-thread-3
Task Task 4 is being executed by pool-1-thread-4
Task Task 5 is being executed by pool-1-thread-5
All tasks are finished.

Explanation:

  • The Task class implements the Runnable interface and represents a task that prints its name and the name of the thread executing it.
  • The CachedThreadPoolDemo class creates a cached thread pool using the newCachedThreadPool method.
  • Five tasks are submitted to the executor service.
  • Each task prints its name and the name of the thread executing it.
  • The executor service is shut down gracefully, waiting for up to 60 seconds for tasks to complete.

5. Shutting Down the Thread Pool

It's important to properly shut down the ExecutorService to release resources. You can shut it down gracefully or forcefully.

Graceful Shutdown:

executorService.shutdown();
try {
    if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
        executorService.shutdownNow();
    }
} catch (InterruptedException e) {
    executorService.shutdownNow();
}

Forceful Shutdown:

executorService.shutdownNow();

6. Conclusion

The newCachedThreadPool method in the Executors class provides a convenient way to create a thread pool that can dynamically adjust the number of threads based on the workload. This type of thread pool is suitable for applications that launch many short-lived tasks. By using newCachedThreadPool, you can efficiently manage and execute tasks in your applications.

Happy coding!

Comments

  1. I see your most of blog are java tutorials. Your website if so much helpful for a Java programmer. Every person who is interested to learn the Java language, I think they need to follow this website. At this time lots of software company hire java programmer for build a software for good price. So java programmer has a good demand. Thanks for your valuable article.

    ReplyDelete

Post a Comment

Leave Comment