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 Fixed Thread Pool

farenda 2015-10-12 0

Problem:

How and when use Java Fixed Thread Pool? In this post we’ll show the ExecutorService in action and describe its characteristics.

Solution:

java.util.concurrent.Executors class has a number of static factory methods to create predefined ExecutorServices. There are two methods to create executors with Fixed Thread Pool:

  • ExecutorService newFixedThreadPool(int nThreads)
    Creates a thread pool with nThreads and executes at most as many tasks.
  • ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory)
    Creates a thread pool with nThreads and executes at most as many tasks. When needed new threads are created using provided ThreadFactory.

In the following example we’ll use the first method to create a pool that executes at most two tasks at the same time. If you run the example you will see that they report count in pairs:

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 FixedThreadPoolExecutorExample {

    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) {
        int nThreads = 2;
        System.out.printf("Starting Fixed Thread Pool of %d threads%n", nThreads);
        ExecutorService executor = Executors.newFixedThreadPool(nThreads);
        for (int i = 1; i <= 4; ++i) {
            executor.execute(new Counter(3));
        }
        executor.shutdown();
    }
}
&#91;/sourcecode&#93;

<p> And here's the result of running the above code: </p>


Starting Fixed Thread Pool of 2 threads
Starting counter: 1
Starting counter: 2
counter 1, value: 0
counter 2, value: 0
counter 1, value: 1
counter 2, value: 1
counter 1, value: 2
Finishing counter: 1
Starting counter: 3
counter 2, value: 2
Finishing counter: 2
Starting counter: 4
counter 3, value: 0
counter 4, value: 0
counter 3, value: 1
counter 4, value: 1
counter 3, value: 2
Finishing counter: 3
counter 4, value: 2
Finishing counter: 4

As you can see the threads (and hence tasks) are executed in pairs, which exactly matches the size of our Fixed Thread Pool.

If a thread dies then the pool will create a new one to match specified size.

Fixed Thread Pool creates the threads when it starts and doesn’t waist time later when tasks are submitted. Also, due to its fixed size, there’s no danger going out of number of threads limit, which could in other executors when many tasks would be submitted in short period of time.

Share with the World!
Categories Java Tags java, java-concurrency
Previous: Java ExecutorService example
Next: Java Cached Thread Pool

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