The Programmer's Guide
  • About
  • Algorithm
    • Big O Notation
      • Tree
      • Problems
    • Basic Notes
    • Data Structure Implementation
      • Custom LinkedList
      • Custom Stack
      • Custom Queue
      • Custom Tree
        • Binary Tree Implementation
        • Binary Search Tree Implementation
        • Min Heap Implementation
        • Max Heap Implementation
        • Trie Implementation
      • Custom Graph
        • Adjacency List
        • Adjacency Matrix
        • Edge List
        • Bidirectional Search
    • Mathematical Algorithms
      • Problems - Set 1
      • Problems - Set 2
    • Bit Manipulation
      • Representation
      • Truth Tables
      • Number System
        • Java Program
      • Problems - Set 1
    • Searching
    • Sorting
    • Array Algorithms
    • String Algorithms
    • Tree
      • Tree Traversal Techniques
      • Tree Implementation
      • Applications of Trees
      • Problems - Set 1
    • Graph
      • Graph Traversal Techniques
      • Shortest Path Algorithms
      • Minimum Spanning Tree (MST) Algorithms
    • Dynamic Programming
      • Problems - Set 1
    • Recursion
    • Parallel Programming
    • Miscellaneous
      • Problems - Set 1
  • API
    • API Basics
      • What is an API?
      • Types of API
        • Comparison - TBU
      • Synchronous vs Asynchronous API
    • API Architecture
      • Synchronous & Asynchronous Communication
    • API Specification
  • Cloud Computing
    • Cloud Fundamentals
      • Cloud Terminology
      • Core Terminology
      • Cloud Models
      • Cloud Service Models
      • Benefits, Challenges and Risk of Cloud Computing
      • Cloud Ecosystem
  • Database
    • DBMS
      • Types of DBMS
        • Relational DBMS (RDBMS)
        • NoSQL DBMS
        • Object-Oriented DBMS (OODBMS)
        • Columnar DBMS
        • In-Memory DBMS
        • Distributed DBMS
        • Cloud-Based DBMS
        • Hierarchical DBMS
      • DBMS Architecture
      • DBMS Structure
    • SQL Databases
      • Terminology
      • RDBMS Concepts
        • Entity Relationship Diagram (ERD)
          • ERD Examples
        • Normalization
        • Denormalization
        • ACID & BASE Properties
          • ACID Properties
          • BASE Properties
        • Locking and Unlocking
      • SQL Fundamentals
        • SQL Commands
          • DDL (Data Definition Language)
          • DML (Data Manipulation Language)
          • DCL (Data Control Language)
          • TCL (Transaction Control Language)
          • DQL (Data Query Language)
        • SQL Operators
          • INTERSECT
          • EXCEPT
          • MINUS
          • IN and NOT IN
          • EXISTS and NOT EXISTS
        • SQL Clauses
          • Joins
          • OVER
          • WITH
          • CONNECT BY
          • MODEL
          • FETCH FIRST
          • KEEP
          • OFFSET with FETCH
        • SQL Functions
          • Oracle Specific
        • SQL Data Types
          • Numeric Types
          • Character Types
          • Date & Time Types
          • Large Object Types
        • Others
          • Indexing
      • Vendor Specific Concepts
        • Oracle Specific
          • Data Types
          • Character Set
          • Rownum, Rowid, Urowid
          • Order of Execution of the query
          • Keys
          • Tablespace
          • Partition
      • Best Practice
      • Resources & References
        • O’Reilly SQL Cookbook (2nd Edition)
          • 1. Retrieving Records
          • 2. Sorting Query Results
          • 3. Working with Multiple Tables
          • 4. Inserting, Updating, and Deleting
          • 5. Metadata Queries
          • 6. Working with Strings
          • 7. Working with Numbers
          • 8. Date Arithmetic
          • 9. Date Manipulation
          • 10. Working with Ranges
          • 11. Advanced Searching
          • 12. Reporting and Reshaping
          • 13. Hierarchical Queries
          • 14. Odds 'n' Ends
    • SQL vs NoSQL
    • Best Practices
  • Git
    • Commands
      • Setup and Configuration Commands
      • Getting and Creating Projects
      • Tracking Changes
      • Branching and Merging
      • Sharing and Updating Projects
      • Inspection and Comparison
      • Debugging
      • Patching
      • Stashing and Cleaning
      • Advanced Manipulations
    • Workflows
      • Branching Strategies
        • Git Flow
        • Trunk-Based Development
        • GitHub Flow
        • Comparison
      • Merge Strategies
        • Merge
        • Rebase
        • Squash
        • Fast-forward vs No-fast-forward
        • MR vs PR
      • Conflict Resolution
        • Handling Merge Conflicts
        • Merge Conflicts
        • Rebase Conflicts
        • Divergent Branches After git pull
        • Force Push
      • Patch & Recovery
        • Cherry-pick strategies
        • Revert vs Reset
        • Recover from a bad rebase
      • Rebasing Practices
        • Merge vs Rebase
        • Rebase develop branch on main branch
      • Repository Management
        • Working Directory
        • Mirror a repository
        • Convert a local folder to a Git repo
        • Backup and restore a Git repository
  • Java
    • Java Installation
    • Java Distributions
    • Java Platform Editions
      • Java SE
      • Java EE
      • Jakarta EE
      • Java ME
      • JavaFX
    • Java Overview
      • OOP Principles
        • Encapsulation
        • Inheritance
        • Polymorphism
        • Abstraction
          • Abstract Class & Method
          • Interface
            • Functional Interfaces
            • Marker Interfaces
          • Abstract Class vs Interface
      • OOP Basics
        • What is a Class?
          • Types of Classes
        • What is an Object?
          • Equals and HashCode
            • FAQ
          • Shallow Copy and Deep Copy
          • Ways to Create Object
          • Serialization & Deserialization
        • Methods & Fields
          • Method Overriding & Overloading
          • Method Signature & Header
          • Variables
        • Constructors
        • Access Modifiers
      • Parallelism & Concurrency
        • Ways to Identify Thread Concurrency or Parallelism
        • Thread Basics
          • Thread vs Process
          • Creating Threads
          • Thread Context Switching
          • Thread Lifecycle & States
          • Runnable & Callable
          • Types of Threads
          • Thread Priority
        • Thread Management & Synchronisation
          • Thread Resource Sharing
          • Thread Synchronization
            • Why is Synchronization Needed?
            • Synchronized Blocks & Methods
          • Thread Lock
            • Types of Locks
            • Intrinsic Lock (Monitor Lock)
            • Reentrant Lock
          • Semaphore
          • Thread Starvation
          • Thread Contention
          • Thread Deadlock
          • Best Practices for Avoiding Thread Issues
      • Keywords
        • this
        • super
        • Access Modifiers
      • Data Types
        • Default Values
        • Primitive Types
          • byte
          • short
          • int
          • long
          • float
          • double
          • char
          • boolean
        • Non-Primitive (Reference) Types
          • String
            • StringBuilder
            • StringBuffer
              • Problems
            • Multiline String
            • Comparison - String, StringBuilder & StringBuffer
          • Array
          • Collections
            • List
              • Array vs List
              • ArrayList
              • Vector
                • Stack
                  • Problems
              • LinkedList
            • Queue
              • PriorityQueue
              • Deque (Double-Ended Queue)
                • ArrayDeque
                • ConcurrentLinkedDeque - TBU
                • LinkedBlockingDeque - TBU
            • Map
              • HashMap
              • Hashtable
              • LinkedHashMap
              • ConcurrentHashMap
              • TreeMap
              • EnumMap
              • WeakHashMap
            • Set
              • HashSet
              • LinkedHashSet
              • TreeSet
              • EnumSet
              • ConcurrentSkipListSet
              • CopyOnWriteArraySet
        • Specialized Classes
          • BigInteger
          • BigDecimal
            • Examples
          • BitSet
          • Date and Time
            • Examples
          • Optional
          • Math
          • UUID
          • Scanner
          • Formatter
            • Examples
          • Properties
          • Regex (Pattern and Matcher)
            • Examples
          • Atomic Classes
          • Random
          • Format
            • NumberFormat
            • DateFormat
            • DecimalFormat
        • Others
          • Object
          • Enum
            • Pre-Defined Enum
            • Custom Enum
            • EnumSet and EnumMap
          • Record
          • Optional
          • System
          • Runtime
          • ProcessBuilder
          • Class
          • Void
          • Throwable
            • Error
            • Exception
              • Custom Exception Handling
              • Best Practice
            • Error vs Exception
            • StackTraceElement
    • Java Features by Version
      • How New Java Features are Released ?
      • Java Versions
        • Java 8
        • Java 9
        • Scoped Values
        • Unnamed Variables & Patterns
      • FAQ
    • Concepts
      • Set 1
        • Streams
          • flatmap
          • Collectors Utility Class
          • Problems
        • Functional Interfaces
          • Standard Built-In Interfaces
          • Custom Interfaces
        • Annotation
          • Custom Annotation
          • Meta Annotation
        • Generics
          • Covariance and Invariance
        • Asynchronous Computation
          • Future
          • CompletableFuture
          • Future v/s CompletableFuture
          • ExecutorService
            • Thread Pool
            • Types of Work Queues
            • Rejection Policies
            • ExecutorService Implementations
            • ExecutorService Usage
          • Locks, Atomic Variables, CountDownLatch, CyclicBarrier - TBU
          • Parallel Streams, Fork/Join Framework,Stream API with Parallelism - TBU
      • Set 2
        • Standards
          • ISO Standards
          • JSR
            • JSR 303, 349, 380 (Bean Validation)
        • Operator Precedence
      • Set 3
        • Date Time Formatter
        • Validation
      • Set 4
        • Input from User
        • Comparison & Ordering
          • Object Equality Check
          • Comparable and Comparator
            • Comparator Interface
          • Sorting of Objects
          • Insertion Ordering
    • Packages
      • Core Packages
        • java.lang
          • java.lang.System
          • java.lang.Thread
      • Jakarta Packages
        • jakarta.validation
        • javax.validation
      • Third-party Packages
    • Code Troubleshoot
      • Thread Dump
      • Heap Dump
    • Code Quality & Analysis
      • ArchUnit
      • Terminologies
        • Cyclic dependencies
    • Code Style
      • Naming Convention
      • Package Structure
      • Formatting
      • Comments and Documentation
      • Imports
      • Exception Handling
      • Class Structure
      • Method Guidelines
      • Page 1
      • Code Smells to Avoid
      • Lambdas and Streams Style
      • Tools
    • Tools
      • IntelliJ IDEA
        • Shortcuts for MAC
      • Apache JMeter
        • Examples
      • Thread Dump Capture
        • jstack
        • VisualVM - TBU
        • jcmd - TBU
        • JConsole - TBU
        • YourKit Java Profiler - TBU
        • Eclipse MAT - TBU
        • IntelliJ IDEA Profiler - TBU
        • AppDynamics - TBU
        • Dynatrace - TBU
        • Thread Dump Analyzers - TBU
      • Heap Dump Capture
        • jmap
        • VisualVM - TBU
        • jcmd - TBU
        • Eclipse MAT (Memory Analyzer Tool) - TBU
        • IntelliJ IDEA Profiler - TBU
        • YourKit Java Profiler - TBU
        • AppDynamics - TBU
        • Dynatrace - TBU
        • Kill -3 Command - TBU
        • jhat (Java Heap Analysis Tool) - TBU
        • JVM Options - TBU
      • Wireshark
        • Search Filters
    • Best Practices
      • Artifact and BOM Versioning
  • Maven
    • Installation
    • Local Repository & Configuration
    • Command-line Options
    • Build & Lifecycle
    • Dependency Management
      • Dependency
        • Transitive Dependency
        • Optional Dependency
      • Dependency Scope
        • Maven Lifecycle and Dependency Scope
      • Dependency Exclusions & Overrides
      • Bill of Materials (BOM)
      • Dependency Conflict Resolution
      • Dependency Tree & Analysis
      • Dependency Versioning Strategies
    • Plugins
      • Build Lifecycle Management
      • Dependency Management
      • Code Quality and Analysis
      • Documentation Generation
      • Code Generation
      • Packaging and Deployment
      • Reporting
      • Integration and Testing
      • Customization and Enhancement
        • build-helper-maven-plugin
        • properties-maven-plugin
        • ant-run plugin
        • exec-maven-plugin
        • gmavenplus-plugin
      • Performance Optimization
    • FAQs
      • Fixing Maven SSL Issues: Unable to Find Valid Certification Path
  • Spring
    • Spring Basics
      • What is Spring?
      • Why Use Spring
      • Spring Ecosystem
      • Versioning
      • Setting Up a Spring Project
    • Core Concepts
      • Spring Core
        • Dependency Injection (DI)
        • Stereotype Annotation
      • Spring Beans
        • Bean Lifecycle
        • Bean Scope
          • Singleton Bean
        • Lazy & Eager Initialization
          • Use Case of Lazy Initialization
        • BeanFactory
        • ApplicationContext
      • Spring Annotations
        • Spring Boot Specific
        • Controller Layer (Web & REST Controllers)
    • Spring Features
      • Auto Configuration
        • Spring Boot 2: spring.factories
        • Spring Boot 3: spring.factories
      • Spring Caching
        • In-Memory Caching
      • Spring AOP
        • Before Advice
        • After Returning Advice
        • After Throwing Advice
        • After (finally) Advice
        • Around Advice
      • Spring File Handling
      • Reactive Programming
        • Reactive System
        • Reactive Stream Specification
        • Project Reactor
          • Mono & Flux
      • Asynchronous Computation
        • @Async annotation
      • Spring Security
        • Authentication
          • Core Components
            • Security Filter Chain
              • HttpSecurity
              • Example
            • AuthenticationManager
            • AuthenticationProvider
            • UserDetailsService
              • UserDetails
              • PasswordEncoder
            • SecurityContext
            • SecurityContextHolder
            • GrantedAuthority
            • Security Configuration (Spring Security DSL)
          • Authentication Models
            • One-Way Authentication
            • Mutual Authentication
          • Authentication Mechanism
            • Basic Authentication
            • Form-Based Authentication
            • Token-Based Authentication (JWT)
            • OAuth2 Authentication
            • Multi-Factor Authentication (MFA)
            • SAML Authentication
            • X.509 Certificate Authentication
            • API Key Authentication
            • Remember-Me Authentication
            • Custom Authentication
          • Logout Handling
        • Authorization
        • Security Filters and Interceptors
        • CSRF
          • Real-World CSRF Attacks & Prevention
        • CORS
        • Session Management and Security
        • Best Practices
      • Spring Persistence
        • JDBC
          • JDBC Components
          • JDBC Template
          • Transaction Management
          • Best Practices in JDBC Usage
          • Datasource
            • Connection Pooling
              • HikariCP
            • Caching
        • JPA (Java Persistence API)
          • JPA Fundamentals
          • ORM Mapping Annotations
            • 1. Entity and Table Mappings
            • 2. Field/Column Mappings
            • 3. Relationship Mappings
            • 4. Inheritance Mappings
            • 5. Additional Configuration Annotations
          • Querying Data
            • JPQL
            • Criteria API
            • JPA Specification
              • Example - Employee Portal
            • Native SQL Queries
            • Named Queries
            • Query Return Types
            • Pagination & Sorting
              • Example - Employee Portal
            • Projection
          • Fetch Strategies in JPA
        • JPA Implementation
          • Hibernate
            • Properties
            • Example
        • Spring Data JPA
          • Repository Abstractions
          • Entity-to-Table Mapping
          • Derived Query Methods
        • Cross-Cutting Concerns
          • Transactions
          • Caching
          • Concurrency
        • Examples
          • Employee Portal
            • API
    • Distributed Systems & Communication
      • Distributed Scheduling
      • Inter-Service Communication
        • 1. RestTemplate
        • 2. WebClient
        • 3. OpenFeign
        • Retry Mechanism
          • @Retryable annotation
            • Example
    • Security & Data Protection
      • Encoding | Decoding
        • Types
          • Base Encoding
            • Base16 - TBD
              • Encoding and Decoding in Java - TBD
            • Base32
              • Encoding and Decoding in Java
            • Base64 -TBD
              • Encoding and Decoding in Java - TBD
          • Text Encoding - TBD
            • Extended ASCII
              • Encoding and Decoding in Java - TBD
                • ISO-8859-1
                • Windows-1252 - TBD
                • IBM Code Pages - TBD
            • ASCII
              • Encoding and Decoding in Java
        • Java Guidelines
          • Text Encoding Decoding Examples
          • Base Encoding Decoding Examples
          • Best Practices and Concepts
          • Libraries
      • Cryptography
        • Terminology
        • Java Cryptography Architecture (JCA)
        • Key Management
          • Key Generation
            • Tools and Libraries
              • OpenSSL
              • Java Keytool
                • Concept
                • Use Cases
            • Key & Certificate File Formats
          • Key Distribution
          • Key Storage
          • Key Rotation
          • Key Revocation
        • Encryption & Decryption
          • Symmetric Encryption
            • Algorithm
            • Modes of Operation
            • Examples
          • Asymmetric Encryption
            • Algorithm
            • Mode of Operation
            • Examples
    • Utilities & Libraries
      • Apache Libraries
        • Apache Camel
          • Camel Architecture
            • Camel Context
            • Camel Endpoints
            • Camel Components
            • Camel Exchange & MEP
          • Spring Dependency
          • Different Components
            • Camel SFTP
        • Apache Commons Lang
      • MapStruct Mapper
      • Utilities by Spring framework
        • FileCopyUtils
    • General Concepts
      • Spring Boot Artifact Packaging
      • Classpath and Resource Loading
      • Configuration - Mapping Properties to Java Class
      • Validations in Spring Framework
        • Jakarta Validation
          • Jakarta Bean Validation Annotations
    • Practical Guidelines
      • Spring Configuration
      • Spring Code Design
  • Software Testing
    • Software Testing Methodologies
      • Functional Testing
      • Non Functional Testing
    • Software Testing Life Cycle (STLC)
    • Integration Test
      • Dynamic Property Registration
    • Java Test Framework
      • JUnit
        • JUnit 4
          • Examples
        • JUnit 5
          • Examples
        • JUnit 4 vs JUnit 5
  • System Design
    • Foundations
      • Programming Paradigms
      • Object-Oriented Design
        • SOLID Principles
        • GRASP Principles
        • Composition
        • Aggregation
        • Association
      • Design Pattern
        • Creational Pattern
        • Structural Pattern
        • Behavioral Pattern
        • Examples
          • Data Collector
          • Payment Processor
        • Design Enhancements
          • Fluent API Design
            • Examples
    • Architectural Building Blocks
      • CAP Theorem
      • Load Balancer
        • Load Balancer Architecture
        • Load Balancing in Java Microservices
          • Client-Side Load Balancing Example
          • Server-Side Load Balancing Example
        • Load Balancer Monitoring Tool
      • Scaling
        • Vertical Scaling (Scaling Up)
        • Horizontal Scaling (Scaling Out)
        • Auto-Scaling
        • Database Scaling via Sharding
      • Caching
        • Pod-Level vs Distributed Caching
      • Networking Metrics
        • Types of Delay
        • Scenario
      • System Characteristics
      • Workload Types
      • Resilience & Failure Handling
    • Performance
      • Why Is My API Sometimes Slow ?
    • Security
      • Security by Design
      • Zero Trust Security Model
      • Zero Trust Architecture
      • Principles
        • CIA
        • Least Privilege Principle
        • Defense in Depth
      • Security Threats & Mitigations
        • OWASP
          • Top 10 Security Threats
          • Application Security Verification Standard
          • Software Assurance Maturity Model
          • Dependency Check
          • CSRFGuard
          • Cheat Sheets
          • Security Testing Guide
          • Threat Dragon
        • Threat Modeling
      • Compliance & Regulation
        • PCI DSS
    • Deployment Patterns
    • Diagrams
      • UML Diagrams
        • PlantUML
          • Class Diagram
          • Object Diagram
          • Sequence Diagram
          • Use Case Diagram
          • Activity Diagram
          • State Diagram
          • Architecture Diagram
          • Component Diagram
          • Timing Diagram
          • ER Diagram (Entity-Relationship)
          • Network Diagram
    • Common Terminologies
    • Problems
      • Reference Materials
      • Cache Design
  • Interview Guide
    • Non-Technical
      • Behavioural or Introductory Guide
      • Project Specific
    • Technical
      • Java Interview Companion
        • Java Key Concepts
          • Set 1
          • Set 2
        • Java Code Snippets
        • Java Practice Programs
          • Set 3 - Strings
          • Set 4 - Search
          • Set 5 - Streams and Collection
      • SQL Interview Companion
        • SQL Practice Problems
          • Set 1
      • Spring Interview Companion
        • Spring Key Concepts
          • Set 1 - General
          • Set 2 - Core Spring
        • Spring Code Snippets
          • JPA
      • Application Server
      • Maven
      • Containerized Application
      • Microservices
    • General
      • Applicant Tracking System (ATS)
      • Flowchart - How to Solve Coding Problem?
Powered by GitBook
On this page
  • About
  • 1. ThreadPoolExecutor
  • Key Characteristics
  • Use Cases
  • Example
  • 2. Custom ThreadPoolExecutor
  • Key Characteristics
  • Use Cases
  • Usage Example
  • 3. ScheduledThreadPoolExecutor
  • Key Characteristics
  • Use Cases
  • Usage Example
  • 4. ForkJoinPool
  • Key Characteristics
  • Use Cases
  • Usage Example
  • 5. SingleThreadExecutor
  • Key Characteristics
  • Use Cases
  • Usage Example
  • 6. CachedThreadPool
  • Key Characteristics
  • Use Cases
  • Usage Example
  • 7. Work-Stealing Pool (Java 8+)
  • Key Characteristics
  • Use Cases
  • Usage Example

Was this helpful?

  1. Java
  2. Concepts
  3. Set 1
  4. Asynchronous Computation
  5. ExecutorService

ExecutorService Implementations

About

Java's ExecutorService provides a framework for managing a pool of threads to execute asynchronous tasks. The framework abstracts the creation, execution, and management of threads, making it easier to work with concurrent tasks. Various implementations of ExecutorService cater to different use cases and requirements. Below are some of the ExecutorService implementations in Java.

1. ThreadPoolExecutor

ThreadPoolExecutor is the commonly used and configurable implementation of ExecutorService. It allows for fine-grained control over thread management and task handling.

Key Characteristics

  • Core Pool Size: The minimum number of threads that are always kept alive, even if they are idle.

  • Maximum Pool Size: The maximum number of threads allowed in the pool.

  • Keep-Alive Time: The maximum time that excess idle threads will wait for new tasks before terminating.

  • Work Queue: The queue used for holding tasks before they are executed. Can be ArrayBlockingQueue, LinkedBlockingQueue, SynchronousQueue, etc.

  • Rejected Execution Handler: Defines the policy for handling tasks that cannot be executed (e.g., due to a full queue or pool shutdown). Options include AbortPolicy, CallerRunsPolicy, DiscardPolicy, and DiscardOldestPolicy.

Use Cases

  1. Web Server Request Handling

    • Scenario: A web server managing multiple client requests concurrently.

    • Configuration: Set a fixed number of threads based on server capacity. Use a bounded queue to prevent memory overflow and a rejection policy to handle overloads.

    • Why: Ensures efficient handling of concurrent requests without overloading the server resources.

  2. Background Job Processing

    • Scenario: A system that processes background jobs such as generating reports, processing images, or sending emails.

    • Configuration: Use a fixed thread pool size with a large task queue to buffer tasks.

    • Why: Controls the number of concurrent jobs and prevents excessive resource usage.

  3. Data Pipeline Processing

    • Scenario: A data pipeline that processes incoming data in stages, such as ETL (Extract, Transform, Load) processes.

    • Configuration: Configure a pool with a sufficient number of threads to handle data stages concurrently.

    • Why: Ensures smooth and efficient data flow through the pipeline.

  4. Monitoring and Alerting Systems

    • Scenario: A system that periodically checks various metrics and triggers alerts based on conditions.

    • Configuration: Use a scheduled thread pool with periodic task scheduling.

    • Why: Automates monitoring and ensures timely alerts

Example

ExecutorService executor = new ThreadPoolExecutor(
    10, // core pool size
    20, // maximum pool size
    60L, // keep-alive time
    TimeUnit.SECONDS, // time unit
    new LinkedBlockingQueue<Runnable>(), // work queue
    new ThreadPoolExecutor.CallerRunsPolicy() // rejection policy
);
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolExecutorExample {
    public static void main(String[] args) {
        // Create a ThreadPoolExecutor with 5 core threads and a maximum of 10 threads
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                5, // core pool size
                10, // maximum pool size
                60, // time to keep idle threads alive
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(100) // task queue with a capacity of 100
        );

        // Submit tasks to the executor
        for (int i = 0; i < 20; i++) {
            final int taskId = i;
            executor.submit(() -> {
                System.out.println("Executing task " + taskId + " by " + Thread.currentThread().getName());
                try {
                    Thread.sleep(2000); // Simulate work
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }

        // Shutdown the executor
        executor.shutdown();
    }
}

We can also create a class with name ExecutorConfiguration and add a bean like below.

package com.company.project.config;

import io.micrometer.context.ContextExecutorService;
import io.micrometer.context.ContextSnapshotFactory;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.annotation.Validated;

@Validated
@Configuration
public class ExecutorConfiguration {

    @Bean("myThreadPoolExecutor")
    public Executor executor(ExecutorConfigurationProperties properties) {
        var executorService = new ThreadPoolExecutor(
            properties.getCorePoolSize(),
            properties.getMaxPoolSize(),
            properties.getKeepAliveSeconds(),
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(), // Using unbounded blocking queue to avoid rejection, if any
            new ThreadPoolExecutor.AbortPolicy()
        );
        var traceableExecutor = ContextExecutorService.wrap(executorService,
            ContextSnapshotFactory.builder().build()::captureAll);

        return traceableExecutor;
    }
}


package com.company.project.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.unit.DataSize;
import org.springframework.validation.annotation.Validated;

@Data
@Validated
@Configuration
@ConfigurationProperties("executor.config")
public class ExecutorConfigurationProperties {
    // Thread pool properties
    private int corePoolSize;
    private int maxPoolSize;
    private int keepAliveSeconds;
}

2. Custom ThreadPoolExecutor

For specialized needs, we can extend ThreadPoolExecutor and override its methods to provide custom behaviors, such as logging, monitoring, or modifying task handling.

Key Characteristics

  • Customization: Full control over the executor's behavior, including thread creation, task execution, and termination policies.

Use Cases

  1. Custom Logging and Monitoring

    • Scenario: Tracking task execution times, number of active threads, and queue sizes.

    • Customization: Override methods like beforeExecute(), afterExecute(), and terminated() to add logging.

    • Why: Provides insights into the thread pool's performance and task handling.

  2. Custom Thread Creation

    • Scenario: Setting custom thread names, priorities, or other properties.

    • Customization: Provide a custom ThreadFactory to set specific thread characteristics.

    • Why: Helps in debugging and monitoring by providing meaningful thread names.

  3. Custom Task Rejection Handling

    • Scenario: Specific actions when tasks are rejected, such as logging, retrying, or notifying administrators.

    • Customization: Implement a custom RejectedExecutionHandler to define task rejection behavior.

    • Why: Allows graceful degradation and ensures important tasks are not silently dropped.

  4. Task Prioritization

    • Scenario: Prioritizing certain tasks over others based on business logic.

    • Customization: Use a custom priority queue and comparator to manage task ordering.

    • Why: Ensures high-priority tasks are executed promptly.

Usage Example

class CustomThreadPoolExecutor extends ThreadPoolExecutor {
    public CustomThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }

    @Override
    protected void beforeExecute(Thread t, Runnable r) {
        super.beforeExecute(t, r);
        // Custom logic before task execution
    }

    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        super.afterExecute(r, t);
        // Custom logic after task execution
    }

    @Override
    protected void terminated() {
        super.terminated();
        // Custom logic on termination
    }
}

Assuming, we are building an order processing system where each order goes through multiple steps like validation, payment processing, inventory update, and notification. Each step needs to be handled concurrently for efficiency.

import java.util.concurrent.*;

public class CustomThreadPoolExecutor extends ThreadPoolExecutor {

    public CustomThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }

    @Override
    protected void beforeExecute(Thread t, Runnable r) {
        super.beforeExecute(t, r);
        System.out.println("Thread " + t.getName() + " is about to execute task: " + r);
        // Custom logic before task execution, e.g., logging, security checks, etc.
    }

    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        super.afterExecute(r, t);
        if (t != null) {
            System.out.println("Exception occurred during execution: " + t.getMessage());
        }
        System.out.println("Task " + r + " has completed execution.");
        // Custom logic after task execution, e.g., collecting metrics, auditing, etc.
    }

    @Override
    protected void terminated() {
        super.terminated();
        System.out.println("ThreadPool is shutting down. Performing cleanup.");
        // Custom logic on termination, e.g., resource deallocation, final reporting, etc.
    }

    public static void main(String[] args) {
        // Configure the custom ThreadPoolExecutor
        CustomThreadPoolExecutor executor = new CustomThreadPoolExecutor(
                4, // corePoolSize
                8, // maximumPoolSize
                30, // keepAliveTime
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(100) // workQueue with a capacity of 100
        );

        // Simulate processing orders
        for (int i = 1; i <= 10; i++) {
            int orderId = i;
            executor.submit(() -> processOrder(orderId));
        }

        // Shutdown the executor
        executor.shutdown();
    }

    private static void processOrder(int orderId) {
        System.out.println("Processing order: " + orderId + " in " + Thread.currentThread().getName());
        try {
            // Simulate different processing times for each order
            Thread.sleep((long) (Math.random() * 3000));
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        System.out.println("Order " + orderId + " processed.");
    }
}

3. ScheduledThreadPoolExecutor

ScheduledThreadPoolExecutor is an implementation of ExecutorService that supports scheduling tasks with a delay or periodic execution. It extends ThreadPoolExecutor.

Key Characteristics

  • Delay Scheduling: Allows scheduling tasks to run after a specified delay.

  • Periodic Scheduling: Allows scheduling tasks to run repeatedly with a fixed delay or at a fixed rate.

Use Cases

  1. Periodic Data Backup: Regularly backing up data to prevent data loss.

    • Why: Can schedule tasks to run at fixed intervals.

  2. Scheduled Report Generation: Generating daily or weekly reports.

    • Why: Supports delayed and periodic execution of tasks.

  3. Monitoring and Alerts: Checking system health and sending alerts if thresholds are crossed.

    • Why: Allows periodic checks and actions based on conditions.

  4. Refreshing Cache: Periodically updating cache data from a database or external source.

    • Why: Can refresh cache entries at regular intervals

Usage Example

ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(5);
scheduledExecutor.scheduleAtFixedRate(() -> {
    // Task to execute
}, 0, 10, TimeUnit.SECONDS);

Suppose we want to print the current time every 5 seconds

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ScheduledThreadPoolExample {
    public static void main(String[] args) {
        // Create a ScheduledThreadPoolExecutor with 2 threads
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);

        // Schedule a task to run every 5 seconds
        scheduler.scheduleAtFixedRate(() -> {
            System.out.println("Current time: " + System.currentTimeMillis());
        }, 0, 5, TimeUnit.SECONDS); // Initial delay: 0 seconds, Period: 5 seconds

        // Schedule another task to run after a delay of 10 seconds
        scheduler.schedule(() -> {
            System.out.println("Task executed after 10 seconds delay");
        }, 10, TimeUnit.SECONDS);

        // Optionally, schedule a shutdown after a certain period
        scheduler.schedule(() -> {
            System.out.println("Shutting down scheduler...");
            scheduler.shutdown();
        }, 30, TimeUnit.SECONDS); // Shutdown after 30 seconds
    }
}

4. ForkJoinPool

ForkJoinPool is designed for work-stealing algorithms and is optimized for tasks that can be broken down into smaller pieces (fork) and then joined after completion.

Key Characteristics

  • Work-Stealing: Threads that finish processing their own tasks can "steal" tasks from other threads.

  • RecursiveTask and RecursiveAction: Used to define tasks that return results (RecursiveTask) or do not return results (RecursiveAction).

Use Cases

  1. Parallel Array Processing: Performing operations like sorting, searching, or summing elements in large arrays.

    • Why: Optimized for tasks that can be recursively divided.

  2. Matrix Multiplication: Breaking down large matrix operations into smaller tasks.

    • Why: Can handle computationally intensive tasks efficiently.

  3. Recursive Algorithms: Implementing algorithms like the Fibonacci sequence, divide-and-conquer algorithms, etc.

    • Why: Supports recursive task splitting and joining.

  4. Data Analysis: Analyzing large datasets by dividing the data and processing in parallel.

    • Why: Efficiently utilizes multiple cores for parallel processing.

Usage Example

ForkJoinPool forkJoinPool = new ForkJoinPool();
forkJoinPool.invoke(new RecursiveTaskExample());

Recursive Task to Calculate Sum of an Array

import java.util.concurrent.RecursiveTask;
import java.util.concurrent.ForkJoinPool;

public class ForkJoinPoolExample {
    public static void main(String[] args) {
        // Sample data
        int[] array = new int[1000];
        for (int i = 0; i < array.length; i++) {
            array[i] = i + 1;
        }

        // Create a ForkJoinPool
        ForkJoinPool forkJoinPool = new ForkJoinPool();

        // Submit the task
        Long sum = forkJoinPool.invoke(new SumTask(array, 0, array.length));
        System.out.println("Sum: " + sum);
    }
}

// RecursiveTask to calculate the sum of an array segment
class SumTask extends RecursiveTask<Long> {
    private final int[] array;
    private final int start;
    private final int end;

    private static final int THRESHOLD = 100; // Threshold for splitting tasks

    public SumTask(int[] array, int start, int end) {
        this.array = array;
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        // If the task is small enough, compute directly
        if (end - start <= THRESHOLD) {
            long sum = 0;
            for (int i = start; i < end; i++) {
                sum += array[i];
            }
            return sum;
        } else {
            // Split the task into two subtasks
            int mid = (start + end) / 2;
            SumTask leftTask = new SumTask(array, start, mid);
            SumTask rightTask = new SumTask(array, mid, end);

            // Fork the subtasks and join the results
            leftTask.fork();
            long rightResult = rightTask.compute();
            long leftResult = leftTask.join();
            return leftResult + rightResult;
        }
    }
}

5. SingleThreadExecutor

SingleThreadExecutor ensures that tasks are executed sequentially in a single thread. It is useful for scenarios where thread safety is a concern, and tasks need to be executed in order.

Key Characteristics

  • Single Thread: Ensures that only one thread is active at any given time.

  • Queue: Uses an unbounded queue to hold tasks.

Use Cases

  1. Logging: Ensuring logs are written sequentially to avoid data corruption.

    • Why: Guarantees that tasks are executed one at a time in the order they are submitted.

  2. Single-User Session Handling: Managing stateful operations for a single user.

    • Why: Ensures that operations are processed in a predictable sequence.

  3. UI Task Execution: Executing non-UI blocking background tasks in GUI applications.

    • Why: Prevents UI freezes by handling tasks in a separate thread.

  4. Transaction Management: Managing transactions sequentially to avoid conflicts.

    • Why: Ensures consistent execution order and data integrity.

Usage Example

ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
singleThreadExecutor.submit(() -> {
    // Task to execute
});

Example of logging task

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

public class SingleThreadExecutorExample {
    public static void main(String[] args) {
        // Create a SingleThreadExecutor
        ExecutorService executor = Executors.newSingleThreadExecutor();

        // Submit tasks
        for (int i = 0; i < 5; i++) {
            final int index = i;
            executor.submit(() -> {
                System.out.println("Executing task " + index + " by " + Thread.currentThread().getName());
                // Simulate some work
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }

        // Shutdown the executor
        executor.shutdown();
    }
}

6. CachedThreadPool

CachedThreadPool creates new threads as needed but will reuse previously constructed threads when available. It is suitable for executing many short-lived tasks.

Key Characteristics

  • Thread Reuse: Reuses threads that have become idle.

  • Unbounded Pool: Creates new threads as needed but terminates idle threads after 60 seconds.

Use Cases

  1. Handling Web Requests: Managing a large number of short-lived HTTP requests.

    • Why: Dynamically creates new threads for incoming tasks and reuses idle ones.

  2. Asynchronous Processing: Processing tasks asynchronously, such as sending emails or notifications.

    • Why: Suitable for tasks that may come in bursts but don't require long-running threads.

  3. Parallel Downloads: Downloading multiple files simultaneously.

    • Why: Can spawn multiple threads to handle downloads concurrently.

  4. Batch Processing: Processing large numbers of records in parallel.

    • Why: Adapts to the number of tasks, making it efficient for varying workloads.

Usage Example

ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
cachedThreadPool.submit(() -> {
    // Task to execute
});

Handling Multiple Web Requests

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

public class CachedThreadPoolExample {
    public static void main(String[] args) {
        // Create a CachedThreadPool
        ExecutorService executor = Executors.newCachedThreadPool();

        // Simulate handling multiple web requests
        for (int i = 0; i < 10; i++) {
            final int requestId = i;
            executor.submit(() -> {
                System.out.println("Handling request " + requestId + " by " + Thread.currentThread().getName());
                // Simulate request processing
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }

        // Shutdown the executor
        executor.shutdown();
    }
}

7. Work-Stealing Pool (Java 8+)

Introduced in Java 8, Executors.newWorkStealingPool() creates a ForkJoinPool that uses a work-stealing algorithm. It is designed to optimize CPU usage by allowing idle threads to steal tasks from busy threads. This pool is particularly useful for parallel tasks that are not uniform in size.

Key Characteristics

  • Work-Stealing: Similar to ForkJoinPool, tasks are distributed among worker threads, and idle threads can steal work from busy threads.

  • Parallelism Level: The pool's parallelism level is typically set to the number of available processors.

Use Cases

  1. Parallel Stream Processing: Utilizing parallel streams in Java 8+ for bulk data operations.

    • Why: Optimizes thread usage and workload distribution.

  2. Real-Time Data Processing: Handling real-time data feeds and processing events as they arrive.

    • Why: Balances the load dynamically, making it suitable for unpredictable workloads.

  3. Game Physics and AI: Running parallel tasks for physics calculations or AI decision-making in games.

    • Why: Efficiently handles parallelism for complex, computationally intensive tasks.

  4. Task-Oriented Workloads: Any scenario where the workload can be divided into independent tasks, such as web crawling, data scraping, or simulations.

    • Why: Work-stealing ensures that all available processing power is utilized, even with uneven task distributions.

Usage Example

ExecutorService workStealingPool = Executors.newWorkStealingPool();
workStealingPool.submit(() -> {
    // Task to execute
});

Parallel Processing of Independent Tasks

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

public class WorkStealingPoolExample {
    public static void main(String[] args) {
        // Create a Work-Stealing Pool
        ExecutorService executor = Executors.newWorkStealingPool();

        // Simulate independent tasks with varying workloads
        CompletableFuture<Void> task1 = CompletableFuture.runAsync(() -> {
            System.out.println("Task 1: " + Thread.currentThread().getName());
            try {
                Thread.sleep(3000); // Simulate workload
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }, executor);

        CompletableFuture<Void> task2 = CompletableFuture.runAsync(() -> {
            System.out.println("Task 2: " + Thread.currentThread().getName());
            try {
                Thread.sleep(2000); // Simulate workload
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }, executor);

        CompletableFuture<Void> task3 = CompletableFuture.runAsync(() -> {
            System.out.println("Task 3: " + Thread.currentThread().getName());
            try {
                Thread.sleep(1000); // Simulate workload
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }, executor);

        // Wait for all tasks to complete
        CompletableFuture.allOf(task1, task2, task3).join();
        executor.shutdown();
    }
}
PreviousRejection PoliciesNextExecutorService Usage

Last updated 8 months ago

Was this helpful?