The Programmer's Guide
  • About
  • AI
  • 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
      • Problems - Set 1
    • Sliding Window Programming
      • Problems - Set 1
    • Tree
      • Tree Traversal Techniques
      • Tree Implementation
      • AVL Tree
      • Red-Black Trees
      • Applications of Trees
      • Problems - Set 1
    • Graph
      • Graph Traversal Techniques
      • Shortest Path Algorithms
        • Dijkstra’s Algorithm
      • Minimum Spanning Tree (MST) Algorithms
      • Topological Sort
    • Dynamic Programming
      • Problems - Set 1
    • Greedy Programming
    • Recursion
    • Parallel Programming
      • Problems - Set 1
    • Miscellaneous
      • Problems - Set 1
  • API
    • API Fundamentals
      • Terminology
      • What is an API ?
      • Consumers & Providers
      • Request & Response
      • Types of API
    • API Communication Patterns
      • Synchronous Communication
        • Request-Response Pattern (Blocking)
        • Request-Response Pattern (Non-blocking)
        • Client Polling
      • Asynchronous Communication
        • Request-Response Pattern (Truly Asynchronous)
        • Event-Driven Pattern
        • Publish-Subscribe Pattern
        • Streaming & Real-Time APIs
          • Server-Sent Events (SSE)
          • WebSockets
          • gRPC Streaming
        • Webhooks (HTTP Callbacks)
      • Hybrid or Adaptive Patterns
        • Async Requests with Sync Feedback
        • Request-Response with Async Push Updates
        • Sync-Async Failover Patterns
    • API Styles & Protocols
      • REST API
        • RESTful API Principles
        • HTTP Status Code
        • HTTP Verbs or Methods
        • HTTP Headers
          • Content Type
          • Content-Disposition
        • Query Parameters & Path Parameters
          • Handling Special Characters in URL
    • API Lifecycle Management
      • API Compatibility
        • Backward Compatibility
        • Forward Compatibility
      • API Versioning Strategies
        • REST API Versioning Approaches
        • GraphQL API Versioning Approaches
      • API Deprecation
        • REST API Deprecation Approach
    • Data Handling
      • Pagination
      • Filtering
      • Sorting
      • Field Selection (Projection)
    • Naming Guidelines
      • API Endpoint Naming
      • Parameter Naming
      • Field and Property Naming
      • Error Codes and Messages
      • Versioning Naming
    • API Testing
      • Tools
        • Postman
        • SoapUI
        • Curl
  • 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 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
      • Vendor Specific Concepts
        • Oracle Specific
          • Data Types
            • BLOB
            • Use Case
          • Character Set
          • Rownum, Rowid, Urowid
          • Order of Execution of the query
          • Execution Plan
            • Understand Execution Plan
          • Keys
          • Tablespace
          • Partition
        • Oracle Examples
        • MYSQL Specific
          • Collation
          • Character Set
        • MYSQL Examples
      • 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
    • NoSQL Databases
      • Concepts
        • Characteristics
        • BASE Properties
        • Eventual Consistency
        • Schema-less Design
        • Sharding
        • Partitioning
        • Transactions
        • Aggregation
        • Projections
        • CRUD Operations
      • Data Models
        • Document Store
        • Key-Value Store
        • Column-Family Store
        • Graph Database
        • Multi-Model Database
    • SQL vs NoSQL
      • ACID & BASE Properties
    • Query Concepts & Performance
      • count(1) vs count(*)
      • Access Multiple Schemas in Single Query
      • Subquery vs Joins
      • Single SQL vs PLSQL Query
  • 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
    • Platforms
      • GitHub
      • GitLab
        • Freeze a branch
      • Bitbucket
  • Identity and Access Management (IAM)
    • Authentication
      • Authentication Methods
    • Keycloak
      • Terminologies
      • Token Verification
      • User Federation
        • Settings
          • Provider - LDAP
        • Integrating OpenLDAP
    • LDAP
      • Local OpenLDAP Setup
    • Single Sign-On (SSO)
  • Java
    • Installation & Setup
      • Installation
      • Java Distributions
      • Java Platform Editions
        • Java SE
        • Java EE
        • Jakarta EE
        • Java ME
        • JavaFX
    • Java Evolution
      • Java Feature Introduction Process
      • Java Version History
        • Java 8
        • Java 9
      • FAQ
    • Java Basics
      • OOP Principles
        • Encapsulation
        • Inheritance
          • Method Overriding
          • Constructor Chaining
          • Dynamic Method Dispatch
          • Inheritance vs. Composition
          • Diamond Problem
        • Polymorphism
          • Rules for Polymorphism
        • Abstraction
          • Abstract Class & Method
          • Interface
            • Functional Interfaces
            • Marker Interfaces
          • Abstract Class vs Interface
          • Model as an Interface or abstract class ?
      • 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 Signature & Header
          • Method Overriding & Overloading
          • Variables
        • Constructors
        • Access Modifiers
      • Java Keywords
        • this
        • super
        • null
          • Handle Null Value
        • Access Modifiers
      • Java 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
              • Examples
            • Queue
              • PriorityQueue
              • Deque (Double-Ended Queue)
                • ArrayDeque
            • Map
              • HashMap
              • Hashtable
                • Collision Resolution
              • LinkedHashMap
              • ConcurrentHashMap
              • TreeMap
              • EnumMap
              • WeakHashMap
            • Set
              • HashSet
              • LinkedHashSet
              • TreeSet
              • EnumSet
              • ConcurrentSkipListSet
              • CopyOnWriteArraySet
        • Specialized Classes
          • BigInteger
          • BigDecimal
            • Examples
          • BitSet
          • Date and Time
            • Comparison
            • 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
            • Enum Comparison
          • Record
          • Optional
          • System
          • Runtime
          • ProcessBuilder
          • Class
          • Void
          • Throwable
            • Error
            • Exception
              • Custom Exception Handling
              • Best Practice
            • Error vs Exception
            • StackTraceElement
      • Java Operators
        • Operator Precedence
        • Problems
      • Parallelism & Concurrency
        • Ways to Identify Thread Concurrency or Parallelism
        • Thread Fundamentals
          • Thread vs Process
          • Creating Threads
            • Runnable & Callable
            • Comparison
            • Examples
          • Thread Context Switching
          • Thread Lifecycle & States
          • Types of Threads
          • Thread Priority
          • Memory Sharing Between Threads
          • Thread Completion & JVM Exit
    • Java Internals
      • JVM Overview
        • Architecture
        • Components
        • Lifecycle
        • Command Line Arguments
      • Memory Management
        • References
        • Types of Memory
    • Java Concepts
      • Language Essentials
        • Annotation
          • Annotation Processing
          • Types of Annotations
            • Custom Annotation
              • Use Case
            • Meta Annotation
        • Generics
          • Covariance and Invariance
        • Scoped Values
        • Unnamed Variables & Patterns
      • Concurrency & Multithreading
        • 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
        • Executor Framework
          • ExecutorService
            • Types of Work Queues
            • Rejection Policies
            • ExecutorService Implementations
            • ExecutorService Usage
        • Asynchronous Programming
          • Future
          • CompletableFuture
          • Future v/s CompletableFuture
      • Functional Programming
        • Functional Interfaces
          • Standard Built-In Interfaces
          • Custom Interfaces
        • Streams
          • flatmap
          • Collectors Utility Class
          • Problems
      • Utilities
        • Date Time Formatter
        • Validation
        • Input Handling
        • Comparing & Ordering
          • Object Equality Check
          • Comparable and Comparator
            • Comparator Interface
          • Sorting of Objects
          • Insertion Ordering
      • Specifications & Standards
        • ISO Standards
        • JSR
          • JSR 303, 349, 380 (Bean Validation)
    • Java Packages
      • Core Packages
        • java.lang
          • java.lang.System
          • java.lang.Thread
        • java.net
          • java.net.InetAddress
        • java.nio
          • java.nio.charset
      • Jakarta Packages
        • jakarta.validation
        • javax.validation
      • Third-party Packages
    • Infrastructure & Deployment
      • Java Servers
        • Application Server
        • Web Server
        • Web Server vs Application Server
        • Server vs Container
      • Java Deployment Models
      • Build & Packaging Tools
        • Maven
    • Troubleshooting Java Code
      • Thread Dump
      • Heap Dump
      • Artifact Analysis
    • Code Quality & Analysis
      • Code Smells
        • Types of Code Smells
        • Code Smells to Avoid
      • Anti-Patterns
        • Types of Anti-Patterns
        • Cyclic dependencies
    • Code Style Guidelines
      • Naming Convention
      • Package Structure
      • Formatting
      • Comments and Documentation
      • Imports
      • Exception Handling
      • Class Structure
      • Method Guidelines
      • Lambdas and Streams Style
      • Code Style Tools
    • Java Development Tools
      • IntelliJ IDEA
        • Shortcuts for MAC
      • Apache JMeter
        • Examples
      • Thread Dump Capture
        • jstack
      • Heap Dump Capture
        • jmap
      • Wireshark
        • Search Filters
    • Best Practices
      • Method Chaining
  • Maven
    • Installation
    • Local Repository & Configuration
    • Command-line Options
    • Artifact Coordinates
      • Classifier
    • POM File
    • 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
        • Artifact and BOM Versioning
    • 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
  • Miscellaneous
    • Image
    • Mac
      • Mac Shortcuts
      • Running Oracle DB
  • Spring
    • Spring Basics
      • What is Spring ?
      • Why Use Spring
      • Spring Ecosystem
      • Versioning
      • Setting Up a Spring Project
      • Spring vs Spring Boot
    • General Concepts
      • Spring Boot Artifact Packaging
      • Classpath and Resource Loading
      • REGEX
        • Core Classes
      • Validations in Spring Framework
        • Jakarta Validation
          • Jakarta Bean Validation Annotations
    • Core Concepts
      • Spring Core
        • Dependency Injection (DI)
          • @Autowired
          • @Qualifier
          • @Primary
        • Stereotype Annotation
      • Spring Beans
        • How Spring Beans Differ from Java Beans ?
        • Bean Definition & Naming
        • Bean Lifecycle
        • Bean Scope
          • Singleton Bean
          • Use Case
        • Lazy & Eager Initialization
          • Use Case of Lazy Initialization
        • BeanFactory
        • ApplicationContext
      • Spring Profiles
      • Spring Annotations
        • Annotation Inheritance
        • Commonly Used Annotations
          • Spring Boot Specific
          • Controller Layer (Web & REST Controllers)
      • Spring Configuration
        • Custom Package Scanning
        • @Value for Property Injection
        • Mapping Properties to Java Class
    • 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
        • Use Cases
      • Spring File Handling
        • Reading a File
      • Reactive Programming
        • Reactive System
        • Reactive Stream Specification
        • Project Reactor
          • Mono & Flux
      • Asynchronous Processing
        • @Async annotation
          • Common Issues
        • ThreadPoolExecutor and Queue Management
      • Inter-Service Communication
        • REST Communication
          • 1. RestTemplate
            • Usage
            • Request Customization
            • Handling Responses
            • Exception Handling
            • Asynchronous Execution
            • Configuration
              • Configuring Request Factories
              • Types of Timeouts
            • HTTP Clients with SSL
            • OpenAPI-Generated Clients
              • Use Case: Internal API Calls with OpenAPI Clients
              • Use Case: Internal API Calls with Manual Clients
            • Transition to WebClient
          • 2. WebClient
            • Usage
            • Request Customization
            • Handling Responses
            • Exception Handling
            • Asynchronous Execution
            • Configuration
            • HTTP Clients with SSL
              • Examples
            • OpenAPI-Generated Clients
              • Use Case: Internal API Calls with OpenAPI Clients
              • Use Case: Internal API Calls with Manual Clients
          • 3. OpenFeign
            • Usage
            • Request Customization
            • Handling Responses
            • Exception Handling
            • Asynchronous Execution
            • Configuration
            • HTTP Client with SSL
            • OpenAPI-Generated Clients
              • Use Case: Internal API Calls with OpenAPI Clients
              • Use Case: Internal API Calls with Manual Clients
          • When to Use Which ?
        • Messaging Communication
          • ActiveMQ
            • Architecture Details
            • Version Overview
            • Naming Convention
            • Message Delivery Guarantee
            • Queues and Topics
            • Configuration Properties
            • Concepts
            • ActiveMQ with Spring Boot
            • Common Issues
      • Resilience Patterns
        • Retry Mechanism
          • @Retryable annotation
            • Example
      • 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
            • SQL AST
            • Properties
            • CRUD API Using Hibernate
        • Spring Data JPA
          • Repository Abstractions
          • Entity-to-Table Mapping
          • Derived Query Methods
        • Cross-Cutting Concerns
          • Transactions
          • Caching
          • Concurrency
        • Common Issues
          • Dead Lock
        • Liquibase
          • Installation & Setup
          • Change Tracking & Locking
          • Liquibase with Spring Boot
          • Liquibase CLI
          • Use Case
        • Examples
          • Employee Portal
            • API
      • Spring Scheduling
        • Cron Expression
        • Distributed Scheduling
          • ShedLock
      • Thymeleaf Integration
    • Security & Data Protection
      • Encoding | Decoding
        • Base Encoding
          • Base32
            • Encoding and Decoding in Java
        • Text Encoding
          • Extended ASCII
          • ASCII
            • Encoding and Decoding in Java
        • Base Encoding Decoding Examples
        • Text Encoding Decoding Examples
        • Best Practices and Concepts
      • 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
        • MAC & HMAC
        • KDF
          • Salt & Nonce
        • Pseudorandom Number Generators (PRNGs)
    • Utilities & Libraries
      • Jackson ObjectMapper
      • Apache Libraries
        • Apache Camel
          • Camel Architecture
            • Camel Context
            • Camel Endpoints
            • Camel Components
            • Camel Exchange & MEP
          • Spring Dependency
          • Different Components
            • Camel SFTP
        • Apache Commons Lang
          • StringUtils
          • ArrayUtils
          • NumberUtils
          • SystemUtils
          • RandomStringUtils
          • DateUtils
          • EqualsBuilder & HashCodeBuilder
          • StopWatch
        • Apache Commons IO
          • FileUtils
        • Apache Commons Validator
      • MapStruct Mapper
      • Lombok
        • Logging with Lombok
      • Utilities by Spring framework
        • StopWatch
      • ArchUnit
    • Deployment & Packaging
      • Inspecting Docker Images
    • Microservices
      • Load Balancing
        • Client-Side Load Balancing Example
        • Server-Side Load Balancing Example
    • Practical Guidelines
      • Spring Coding Conventions
        • Layered Architecture Rules
        • Package & Class Location Rules
        • Dependency Rules
        • Naming Convention Rules
        • Annotation Usage Rules
        • Forbidden API Usage Rules
        • Dependency Cycle Rules
        • Test Layer Rules
        • Documentation & Logging Rules
      • Spring Configuration
      • Spring Code Design
  • Software Testing
    • Testing Fundamentals
      • Software Testing Methodologies
        • Functional Testing
          • Unit Testing
            • Scenario Matrix Template
          • Integration Testing
            • Scenario Matrix Template
          • System Testing
            • Scenario Matrix Template
          • Acceptance Testing
            • Scenario Matrix Template
        • Non Functional Testing
          • Performance Testing
            • Load Testing
              • Terminology
              • Process
              • Strategy
              • Preparation Checklist
              • Metrics to Measure
              • Scenario Matrix Template
            • Stress Testing
              • Scenario Matrix Template
            • Spike Testing
              • Scenario Matrix Template
            • Soak Testing
              • Scenario Matrix Template
            • Scalability Testing
              • Scenario Matrix Template
          • Security Testing
            • Scenario Matrix Template
          • Usability Testing
            • Scenario Matrix Template
          • Reliability Testing
            • Scenario Matrix Template
          • Compatibility Testing
            • Scenario Matrix Template
          • Maintainability Testing
            • Scenario Matrix Template
          • Portability Testing
            • Scenario Matrix Template
          • Recovery Testing
            • Scenario Matrix Template
          • Compliance Testing
            • Scenario Matrix Template
          • Localization Testing
            • Scenario Matrix Template
      • Software Testing Life Cycle (STLC)
    • Levels of Testing
    • Java Test Framework
      • JUnit
        • JUnit 4
        • JUnit 5
          • Parameterized Test
          • Single and Multiple Assertions
        • JUnit 4 vs JUnit 5
      • MockServer
    • Test Automation
      • Manual vs Automated Testing
      • Test Automation Strategies
      • CI/CD Integration
  • System Design
    • Design Foundations
      • Programming Paradigms
      • System Characteristics
      • Object-Oriented Design
        • SOLID Principles
        • GRASP Principles
        • Composition
        • Aggregation
        • Association
      • Design Thinking & Process
        • Problem Framing
        • Use Case Analysis
        • Requirements Gathering
        • Iterative Design Process
      • Workload Types
    • Design Principles & Patterns
      • Software Design Principles
        • DRY
        • KISS
        • YAGNI
        • Separation of Concerns
        • Encapsulation & Abstraction
        • Modularity & Reusability
      • Design Pattern
        • Creational Pattern
        • Structural Pattern
        • Behavioral Pattern
        • Examples
          • Data Collector
          • Payment Processor
          • Transaction Dispute
          • Payment Validation
        • Design Enhancements
          • Fluent API Design
            • Examples
      • Design Metrics
        • Coupling
        • Cohesion
        • Cyclomatic Complexity
        • Lines of Code (LOC)
        • Halstead Metrics
        • Maintainability Index
    • System Design Methodology
      • Design Layers
        • Low-Level Design (LLD)
        • High-Level Design (HLD)
      • Design 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
    • Architectural Styles
      • System-Level
        • Monolith
        • Microservices
        • Event Driven Architecture
        • Serverless
      • Application-Level
        • Layered Architecture
        • Hexagonal Architecture
        • Clean Architecture
      • How System-Level and Application-Level Work Together ?
      • Trends in Practice
        • Spring Boot Microservice with Clean Architecture
        • Spring Boot Microservice with Hexagonal Architecture
    • Architecture Principles
      • Twelve-Factor App Principles
      • Cloud-Native Principles
      • Reactive Manifesto
      • Infrastructure as Code (IaC)
      • DevOps Principles
      • Design for Failure
      • CAP Theorem
    • Architectural Building Blocks
      • Load Balancer
        • Load Balancer Architecture
        • Load Balancer Monitoring Tool
      • Caching
        • Pod-Level vs Distributed Caching
    • Scalability & Reliability
      • Scaling
        • Vertical Scaling (Scaling Up)
        • Horizontal Scaling (Scaling Out)
        • Auto-Scaling
        • Database Scaling via Sharding
      • Resilience & Failure Handling
    • Delivery & Deployment Strategy
      • Feature Flags
      • Traffic Shifting
      • Deployment Patterns
    • Observability
      • Distributed Tracing
        • Fundamentals
        • Tracing Modes
    • Data Handling & Processing
      • MapReduce
        • Example
    • Performance Engineering
      • Why Is My API Sometimes Slow ?
      • Networking Metrics
        • Types of Delay
        • Scenario
    • Security
      • Security Principles
        • CIA
        • Least Privilege Principle
        • Defense in Depth
        • Zero Trust Security Model
        • Security by Design
        • Zero Trust Architecture
      • 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
        • Cyber Attacks
      • Application-Level Security
        • CORS (Cross-Origin Resource Sharing)
      • Secure Software Development Lifecycle
        • Secure Coding Practices
        • DevSecOps
      • Compliance & Regulation
        • GDPR
        • PCI DSS
    • Operational Issues
      • Common Runtime Errors
        • OOM: Unable to Create Native Thread
        • OOM: Requested array size exceeds VM limit
  • Interview Guide
    • Non-Technical
      • Behavioural or Introductory Guide
      • Project Specific
    • Technical
      • Java Interview Companion
        • Java Key Concepts
          • Set 1
          • Set 2
          • Set 3
        • 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
  1. Spring
  2. Utilities & Libraries
  3. Apache Libraries
  4. Apache Commons Lang

StopWatch

PreviousEqualsBuilder & HashCodeBuilderNextApache Commons IO

Last updated 4 days ago

CtrlK
  • About
  • Features
  • Method Reference
  • Use Cases
  • Usage Examples
  • 1. Basic Start and Stop
  • 2. Restart for Multiple Measurements
  • 3. Split and Unsplit (Intermediate Checkpoints)
  • 4. Suspend and Resume
  • 5. Measuring in Different Time Units
  • 6. Logging with Human Readable Format
  • 7. Benchmarking Multiple Algorithms
  • 8. Profiling Stages in a Workflow
  • 9. Integrating with Logging Framework
  • Best Practices

About

The StopWatch class in Apache Commons Lang (org.apache.commons.lang3.time.StopWatch) is a utility designed to measure elapsed time in a precise and convenient manner. It is particularly useful in scenarios such as performance testing, benchmarking, profiling sections of code, or monitoring the execution duration of critical operations. Unlike manually recording system timestamps (System.currentTimeMillis() or System.nanoTime()), StopWatch abstracts away the boilerplate code and provides a clean API for starting, stopping, suspending, resuming, and querying elapsed times.

Features

  1. Start/Stop Timing

    • We can start the stopwatch at a given point in our code and stop it after execution.

    • The elapsed time between these points is recorded.

  2. Suspend/Resume Support

    • The stopwatch can be temporarily suspended and later resumed.

    • This is useful when we want to exclude certain operations from timing.

  3. Split and Unsplit

    • Allows capturing an intermediate time (split) without stopping the stopwatch.

    • Splits are useful when monitoring progress in long-running tasks.

  4. Multiple Time Units

    • Elapsed time can be retrieved in various units: nanoseconds, milliseconds, seconds, minutes, hours, or days.

    • This provides flexibility for both fine-grained benchmarking and high-level reporting.

  5. Thread Safety

    • The basic StopWatch implementation is not thread-safe.

    • For concurrent environments, external synchronization or per-thread instances should be used.

  6. Readable Formatting

    • Supports string formatting of elapsed time in a human-readable style (e.g., 00:01:23.456).

    • Useful for logging and reporting.

Method Reference

Method

Action / Meaning

Constructor

StopWatch()

Creates a new stopwatch (initial state: unstarted).

Core Controls

start()

Starts the stopwatch. Throws IllegalStateException if already started.

stop()

Stops the stopwatch. No more time accumulates until reset.

reset()

Resets stopwatch to the unstarted state (time = 0). Must be called before reusing.

split()

Records the current elapsed time as a split point (does not stop the watch).

unsplit()

Clears the last split. Needed before making another split.

suspend()

Pauses the stopwatch (time is frozen).

resume()

Resumes from a suspended state.

Time Retrieval

getTime()

Returns total elapsed time (in milliseconds) between start and now (or stop).

getNanoTime()

Returns total elapsed time (in nanoseconds) for higher precision.

getSplitTime()

Returns elapsed time (in ms) at the point of the last split.

getSplitNanoTime()

Returns elapsed time (in ns) at the last split.

String Output

toString()

Returns formatted elapsed time as HH:mm:ss.SSS (human-readable).

toSplitString()

Returns formatted split time as HH:mm:ss.SSS.

State Inspection

isStarted()

Returns true if stopwatch has been started.

isStopped()

Returns true if stopwatch has been stopped.

isSuspended()

Returns true if stopwatch is currently suspended.

isStarted()

Returns true if stopwatch has been started (but not necessarily running).

Static Factory (Commons Lang 3.6+)

StopWatch.createStarted()

Creates and starts a new stopwatch in one call.

StopWatch.create()

Creates a new stopwatch in the unstarted state.

Use Cases

  • Performance Testing – Measure the execution time of a method or algorithm to identify bottlenecks.

  • Benchmarking – Compare the performance of multiple implementations of the same logic.

  • Profiling – Track elapsed times for different stages of a workflow using splits.

  • Monitoring – Record execution times for API calls, database queries, or batch processes.

  • Operational Logging – Add duration details in logs for observability and debugging.

Usage Examples

1. Basic Start and Stop

The simplest use case is measuring elapsed time for a block of code.

import org.apache.commons.lang3.time.StopWatch;

public class StopWatchExample {
    public static void main(String[] args) throws InterruptedException {
        StopWatch watch = new StopWatch();

        watch.start(); // Start timing
        Thread.sleep(2000); // Simulated task (2 seconds)
        watch.stop(); // Stop timing

        System.out.println("Elapsed Time in ms: " + watch.getTime()); 
        // Elapsed Time in ms: 2005
    }
}

2. Restart for Multiple Measurements

If we want to reuse the same stopwatch for different measurements, use reset() and start() again.

StopWatch watch = new StopWatch();

watch.start();
Thread.sleep(1000);
watch.stop();
System.out.println("Task 1 time (ms): " + watch.getTime());
// Task 1 time (ms): 1005

watch.reset();
watch.start();
Thread.sleep(1500);
watch.stop();
System.out.println("Task 2 time (ms): " + watch.getTime());
// Task 2 time (ms): 1505

3. Split and Unsplit (Intermediate Checkpoints)

Splits let us measure checkpoints without stopping the stopwatch.

StopWatch watch = new StopWatch();

watch.start();
Thread.sleep(1000);
watch.split();
System.out.println("Split 1 (ms): " + watch.getSplitTime());
// Split 1 (ms): 1004

Thread.sleep(2000);
watch.split();
System.out.println("Split 2 (ms): " + watch.getSplitTime());
// Split 2 (ms): 3010

watch.unsplit(); // Clear split state
watch.stop();
System.out.println("Total time (ms): " + watch.getTime());
// Total time (ms): 3010
StopWatch sw = new StopWatch();
sw.start();

// Step 1: Data Extraction
Thread.sleep(1000); // simulate 1s
sw.split();
System.out.println("After Extraction: " + sw.toSplitString()); 
// After Extraction: 00:00:01.006

// Clear split so we can reuse it
sw.unsplit();

// Step 2: Data Transformation
Thread.sleep(2000); // simulate 2s
sw.split();
System.out.println("After Transformation: " + sw.toSplitString()); 
// After Transformation: 00:00:03.033

// Again clear split
sw.unsplit();

// Step 3: Data Load
Thread.sleep(1500); // simulate 1.5s
sw.split();
System.out.println("After Loading: " + sw.toSplitString()); 
// After Loading: 00:00:04.537

sw.stop();
System.out.println("Total Time: " + sw.toString()); 
// Total Time: 00:00:04.537

4. Suspend and Resume

When certain parts of code shouldn’t be included in measurement, use suspend/resume.

StopWatch watch = new StopWatch();

watch.start();
Thread.sleep(1000);

watch.suspend();  // Pause timing
Thread.sleep(2000); // Excluded from timing
watch.resume();   // Resume timing

Thread.sleep(1000);
watch.stop();

System.out.println("Elapsed Time (ms, excluding suspend): " + watch.getTime());
// Elapsed Time (ms, excluding suspend): 2005

Output: Approximately 2000 ms (1 sec before + 1 sec after, 2 sec suspended excluded).

5. Measuring in Different Time Units

StopWatch provides elapsed time in multiple units.

StopWatch watch = new StopWatch();

watch.start();
Thread.sleep(1234);
watch.stop();

System.out.println("Elapsed Time in ns: " + watch.getNanoTime());
// Elapsed Time in ns: 1239132292
System.out.println("Elapsed Time in ms: " + watch.getTime());
// Elapsed Time in ms: 1239

6. Logging with Human Readable Format

The stopwatch can output a nicely formatted string (HH:mm:ss.SSS).

StopWatch watch = new StopWatch();

watch.start();
Thread.sleep(3750); // 3.75 seconds
watch.stop();

System.out.println("Formatted time: " + watch.toString());
// Formatted time: 00:00:03.752

7. Benchmarking Multiple Algorithms

We can measure and compare performance of different implementations.

StopWatch watch = new StopWatch();

// Algorithm A
watch.start();
runAlgorithmA();
watch.stop();
System.out.println("Algorithm A took: " + watch.getTime() + " ms");

watch.reset();

// Algorithm B
watch.start();
runAlgorithmB();
watch.stop();
System.out.println("Algorithm B took: " + watch.getTime() + " ms");

8. Profiling Stages in a Workflow

Using splits for stage-wise profiling.

StopWatch watch = new StopWatch();

watch.start();

loadData();
watch.split();
System.out.println("Load Data: " + watch.getSplitTime() + " ms");

processData();
watch.split();
System.out.println("Process Data: " + watch.getSplitTime() + " ms");

saveResults();
watch.stop();
System.out.println("Save Results: " + watch.getTime() + " ms");

9. Integrating with Logging Framework

Often used with SLF4J for structured logs.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LoggingExample {
    private static final Logger log = LoggerFactory.getLogger(LoggingExample.class);

    public static void main(String[] args) throws InterruptedException {
        StopWatch watch = new StopWatch();

        watch.start();
        Thread.sleep(1500);
        watch.stop();

        log.info("Task execution completed in {}", watch.toString());
        // Task execution completed in 00:00:01.505
    }
}

Best Practices

1. Always Stop Before Reuse

  • Best Practice: A StopWatch must be stopped before calling reset() or starting again.

  • Pitfall: Forgetting to stop and directly calling start() will throw an IllegalStateException.

2. Use Reset for Multiple Measurements

  • Best Practice: Call reset() before starting a new measurement cycle.

  • Pitfall: Without reset, elapsed times accumulate across runs, leading to misleading results.

3. Use Suspend/Resume Carefully

  • Best Practice: Suspend timing when executing operations that should not count (like sleeping, waiting for external systems).

  • Pitfall: Forgetting to call resume() will lead to under-reporting elapsed time.

4. Prefer toString() for Logging

  • Best Practice: Use toString() for human-readable log output (HH:mm:ss.SSS).

  • Pitfall: Printing getTime() (ms only) is less meaningful for long-running tasks.

5. Benchmark with Warmup

  • Best Practice: For performance benchmarking (e.g., comparing algorithms), always do a warm-up run (JVM JIT optimization may skew first measurements).

  • Pitfall: Running StopWatch only once and assuming results are representative of real performance.

6. Avoid Multi-Threaded Sharing

  • Best Practice: Each thread should have its own StopWatch instance.

  • Pitfall: Sharing a single StopWatch across threads is not thread-safe and leads to corrupted timings.

7. Measure Specific Sections with Splits

  • Best Practice: Use split() to capture intermediate milestones without stopping the clock.

  • Pitfall: Forgetting to call unsplit() before using some operations (like another split) may throw exceptions.

8. Choose the Right Time Unit

  • Best Practice: Use getNanoTime() for precise measurement (e.g., micro-benchmarking).

  • Pitfall: Using only getTime() (ms precision) may lose accuracy in very fast-running tasks.

9. Do Not Mix StopWatch with System.currentTimeMillis()

  • Best Practice: Stick to one timing approach (StopWatch provides consistent, encapsulated API).

  • Pitfall: Mixing with manual timestamp differences may lead to confusion.

10. Clean Logging

  • Best Practice: Wrap StopWatch usage inside try/finally for guaranteed stop and log output.

  • Pitfall: Forgetting to stop a stopwatch in case of exceptions can leave it in an invalid state.

StopWatch watch = new StopWatch();
try {
    watch.start();
    // business logic
} finally {
    watch.stop();
    log.info("Execution completed in {}", watch);
}