Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Java Cached Thread Pool

farenda 2015-10-13 0

Problem:

How and when use Java Cached Thread Pool? In the previous post we’ve shown how Fixed Thread Pool works. In the current example we’ll show how ExecutorService behaves when using Cached Thread Pool.

Solution:

Executors class from java.util.concurrent package has two helper methods that allows to create executors with cached thread pools:

  • ExecutorService newCachedThreadPool()
    Creates a thread pool that will create new threads when needed and reuse existing, while they are in the cache.
  • ExecutorService newCachedThreadPool(ThreadFactory threadFactory)
    It’s like the above method, but allows to construct threads in own way.

What’s important the cache keeps unused threads for 60 seconds, after which they are removed. So after sometime of inactivity no resources are used.

package com.farenda.java.util.concurrent;

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

import static java.util.concurrent.TimeUnit.MILLISECONDS;

public class CachedThreadPoolExecutorExample {

    private static class Counter implements Runnable {

        private static int nth = 0;

        private final int id = ++nth;
        private final int number;

        public Counter(int number) {
            this.number = number;
        }

        @Override
        public void run() {
            System.out.println("Starting counter: " + id);
            for (int i = 0; i < number; ++i) {
                try {
                    MILLISECONDS.sleep(300);
                } catch (InterruptedException e) {
                    // ignore
                }
                System.out.printf("counter %d, value: %d%n", id, i);
            }
            System.out.println("Finishing counter: " + id);
        }
    }

    public static void main(String&#91;&#93; args) {
        System.out.println("Starting Cached Thread Pool");
        ExecutorService executor = Executors.newCachedThreadPool();
        for (int i = 1; i <= 4; ++i) {
            executor.execute(new Counter(3));
        }
        executor.shutdown();
    }
}
&#91;/sourcecode&#93;

<p> And the result of running the example: </p>


Starting Cached Thread Pool
Starting counter: 1
Starting counter: 2
Starting counter: 3
Starting counter: 4
counter 1, value: 0
counter 4, value: 0
counter 3, value: 0
counter 2, value: 0
counter 1, value: 1
counter 4, value: 1
counter 3, value: 1
counter 2, value: 1
counter 1, value: 2
counter 3, value: 2
counter 2, value: 2
Finishing counter: 2
counter 4, value: 2
Finishing counter: 4
Finishing counter: 1
Finishing counter: 3

The output clearly shows that the executor immediately starts as many threads as there are needed to handle submitted tasks.

Cached Thread Pool Executor is a good fit when developing a program or it creates short lived threads. The pool has a drawback of allocating thread resources when a new thread is needed, so when fast task handling is needed better use fixed pools. Also remember about number of allowed threads limit!

Share with the World!
Categories Java Tags java, java-concurrency
Previous: Java Fixed Thread Pool
Next: Java Single Thread Executor

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2021

sponsored
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.Ok