Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Multithreading

Java ExecutorService and Thread Pools

Six orders on six new threads works, but a thousand orders would mean a thousand threads. A fixed pool of three workers packs the same six in two seconds, shutdown closes the entrance while awaitTermination waits, and pools of 1, 3 and 6 take 6, 2 and 1 seconds.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Multithreading

What you will learn

  • Explain the cost of starting a new thread for every task
  • Run tasks on a fixed pool with newFixedThreadPool, submit and close
  • Close a pool with shutdown and wait with awaitTermination
  • See how pool size changes the total time

Before you start

  • Creating threads in Java: Thread, Runnable and lambdas
  • Java lambdas and functional interfaces

Instead of starting a new thread for every small task, keep a few workers and a queue of orders. The workers pick up the next order when they're free. That's a thread pool. Thread names and the order of lines below are from one run; yours may differ.

Six orders, six new threads

package org.studyeasy.s06l06;

public class Ex01_ThreadPerOrder {
    static void pack(int order) {
        String worker = Thread.currentThread().getName();
        System.out.println(worker + " packs order " + order);
        // packing takes 1 second
        try { Thread.sleep(1000); } catch (InterruptedException e) { }
    }

    public static void main(String[] args) {
        int created = 0;
        for (int order = 1; order <= 6; order++) {
            int n = order; // a lambda needs a fixed copy
            new Thread(() -> pack(n)).start(); // a NEW thread each
            created++;
        }
        System.out.println("Threads created: " + created);
    }
}
Threads created: 6
Thread-0 packs order 1
Thread-1 packs order 2
Thread-4 packs order 5
Thread-5 packs order 6
Thread-2 packs order 3
Thread-3 packs order 4

Each order gets its own thread, Thread-0 to Thread-5. int n = order is needed because order changes, and a lambda can only use effectively final variables. Six is fine, but a thousand orders would mean a thousand threads started at once, and every thread costs memory and setup time.

Three workers, six orders

long start = System.currentTimeMillis();
// 3 workers, created once
ExecutorService pool = Executors.newFixedThreadPool(3);
for (int order = 1; order <= 6; order++) {
    int n = order;                  // a lambda needs a fixed copy
    pool.submit(() -> pack(n));     // hand the order to the pool
}
pool.close(); // finish every order, then stop
long seconds = (System.currentTimeMillis() - start) / 1000;
System.out.println("6 orders in " + seconds + " seconds");
pool-1-thread-1 packs order 1
pool-1-thread-2 packs order 2
pool-1-thread-3 packs order 3
pool-1-thread-2 packs order 4
pool-1-thread-1 packs order 5
pool-1-thread-3 packs order 6
6 orders in 2 seconds
submit puts six orders into a queue. A fixed pool keeps three workers, pool-1-thread-1 to 3. They take orders 1, 2 and 3 first; orders 4, 5 and 6 wait in the queue and go to whichever worker is free next. No new threads are started for the orders. 654 queue (waiting) pool.submit(...) x 6 thread-1: order 1, then 5 thread-2: order 2, then 4 thread-3: order 3, then 6 3 threads created once, reused
A fixed pool: a queue of tasks feeding a few reused workers.

Executors.newFixedThreadPool(3) gives an ExecutorService with three workers that it creates once and keeps. submit puts each order in the pool's queue; no new thread starts for it. The three workers take orders 1, 2 and 3; orders 4, 5 and 6 wait and go to whichever worker is free next. Two rounds of one second: 2 seconds. close() waits for every order, then stops the workers. Delete it and the workers wait for more orders, so the program never ends.

Close the entrance, then wait

ExecutorService pool = Executors.newFixedThreadPool(3);
for (int order = 1; order <= 5; order++) {
    int n = order;                  // a lambda needs a fixed copy
    pool.submit(() -> pack(n));
}
pool.shutdown(); // no NEW orders; the ones inside still run
System.out.println("after shutdown: done? " + pool.isTerminated());
// wait here, at most 1 minute
pool.awaitTermination(1, TimeUnit.MINUTES);
System.out.println("after waiting: done? " + pool.isTerminated());
after shutdown: done? false
pool-1-thread-1 packed order 1
pool-1-thread-2 packed order 2
pool-1-thread-3 packed order 3
pool-1-thread-2 packed order 5
pool-1-thread-1 packed order 4
after waiting: done? true

Here pack prints after it sleeps. shutdown() closes the entrance: no new orders, but the ones inside still run, so isTerminated() is false straight after. awaitTermination waits (here up to a minute) for the orders inside to finish; then it's true. Submit order 6 after shutdown() and it's refused with RejectedExecutionException. close() does both steps in one call.

Same six orders, three pool sizes

static long packAll(int workers, int orders) {
    long start = System.currentTimeMillis();
    ExecutorService pool = Executors.newFixedThreadPool(workers);
    for (int order = 1; order <= orders; order++) {
        int n = order;                  // a lambda needs a fixed copy
        pool.submit(() -> pack(n));
    }
    pool.close(); // wait until every order is packed
    return (System.currentTimeMillis() - start) / 1000;
}
pool of 1: 6 orders in 6 seconds
pool of 3: 6 orders in 2 seconds
pool of 6: 6 orders in 1 seconds

One worker packs all six one after another. Three workers pack two each. Six workers give every order its own worker. More workers, less waiting, as long as your machine has the cores and the tasks are independent. A pool needs at least one worker: newFixedThreadPool(0) throws IllegalArgumentException.

Recap

CallWhat it does
Executors.newFixedThreadPool(n)n workers, created once and reused
pool.submit(task)puts a task in the queue
pool.close()waits for every task, then stops
pool.shutdown()no new tasks; the ones inside still run
pool.awaitTermination(...)waits for the tasks inside to finish

A pool can also hand results back; see Callable, Future and CompletableFuture.

Keep going in Java · 70 of 79

Previous
Java volatile and Atomic Variables
Next post
Java Callable, Future and CompletableFuture
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Why Concurrency: Processes, Threads and the Main Thread in Java

Every Java program runs as a process and starts on one thread, main. One cook takes 15 seconds for soup and salad; a second thread, Jack, brings it to 10. Then two threads add to one counter a million times each and count less than 2,000,000.

Creating Threads in Java: Thread, Runnable and Lambdas

Three ways to give a thread its job: an InvoiceMailer that extends Thread, a ReportTask record that implements Runnable, and a lambda. worker.run() prints main, worker.start() prints backup-worker, and two cashiers, Jack and Liam, scan items in an order that changes every run.

Java Thread Lifecycle: sleep, join and interrupt

A courier thread walks from NEW through RUNNABLE and TIMED_WAITING to TERMINATED while main WAITs at join. An interrupt wakes a sleeping download on report-3: one version retries it, the other returns. And a daemon status thread dies when the last user thread ends.

Java Race Conditions and synchronized

Two cashiers each sell a million tickets on one counter and the total comes out short, a different number every run, because sold++ is read, add, write. A synchronized method or a synchronized block on one shared lock gives exactly 2,000,000; a new Object() lock protects nothing.

On this page

  • Six orders, six new threads
  • Three workers, six orders
  • Close the entrance, then wait
  • Same six orders, three pool sizes
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.