<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Ramanjaneyulu Boya</title>
    <description>The latest articles on DEV Community by Ramanjaneyulu Boya (@ramthearchitect).</description>
    <link>https://dev.to/ramthearchitect</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F4243545%2F528a6fd8-05e8-42db-b242-b0eca86fc21f.jpg</url>
      <title>DEV Community: Ramanjaneyulu Boya</title>
      <link>https://dev.to/ramthearchitect</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/ramthearchitect"/>
    <language>en</language>
    <item>
      <title>Designing a Scalable Banking Microservices Architecture</title>
      <dc:creator>Ramanjaneyulu Boya</dc:creator>
      <pubDate>Sun, 06 Dec 2026 18:23:13 +0000</pubDate>
      <link>https://dev.to/ramthearchitect/designing-a-scalable-banking-microservices-architecture-4l93</link>
      <guid>https://dev.to/ramthearchitect/designing-a-scalable-banking-microservices-architecture-4l93</guid>
      <description>&lt;p&gt;Modern banking applications must handle millions of customer interactions, thousands of concurrent transactions, real-time payment processing, and strict security requirements.&lt;/p&gt;

&lt;p&gt;Customers expect instant fund transfers, real-time account balances, uninterrupted digital banking services, and secure transactions.&lt;/p&gt;

&lt;p&gt;Behind these capabilities is a well-designed architecture that can scale independently, handle failures gracefully, maintain data consistency, and ensure high availability.&lt;/p&gt;

&lt;p&gt;Traditional monolithic architectures can become difficult to scale and maintain as banking platforms grow. This is where Microservices Architecture becomes valuable.&lt;/p&gt;

&lt;p&gt;In this article, we will design a scalable banking microservices architecture using Java 21, Spring Boot, Apache Kafka, Redis, PostgreSQL, API Gateway, and cloud-native infrastructure.&lt;/p&gt;

&lt;p&gt;We will explore the architecture, service boundaries, communication patterns, database design, security, scalability, fault tolerance, and real-world banking transaction workflows.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Understanding Banking Microservices Architecture
Microservices architecture divides a large banking application into smaller, independently deployable services.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Each service owns a specific business capability and is responsible for its own business logic and data.&lt;/p&gt;

&lt;p&gt;For example, a banking platform can contain:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Customer Service&lt;/li&gt;
&lt;li&gt;Account Service&lt;/li&gt;
&lt;li&gt;Payment Service&lt;/li&gt;
&lt;li&gt;Fund Transfer Service&lt;/li&gt;
&lt;li&gt;Transaction Service&lt;/li&gt;
&lt;li&gt;Authentication Service&lt;/li&gt;
&lt;li&gt;Fraud Detection Service&lt;/li&gt;
&lt;li&gt;Notification Service&lt;/li&gt;
&lt;li&gt;Loan Service&lt;/li&gt;
&lt;li&gt;Reporting Service
Each service can be developed, deployed, monitored, and scaled independently.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Consider a customer transferring money from one bank account to another.&lt;/p&gt;

&lt;p&gt;Instead of a single application handling everything, multiple services collaborate to complete the transaction.&lt;/p&gt;

&lt;p&gt;Key architectural principle: Each microservice should have a clearly defined business responsibility and a well-defined API or event contract.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fvdsej24wqso3eugk9qcv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fvdsej24wqso3eugk9qcv.png" alt="SCALABLE BANKING MICROSERVICES OVERVIEW" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;High-Level Architecture of a Banking Platform
A scalable banking platform can be organized into multiple architectural layers.
2.1 Client Layer
This layer provides interfaces through which customers and internal banking users interact with the platform.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Examples:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Mobile Banking Application&lt;/li&gt;
&lt;li&gt;Internet Banking Application&lt;/li&gt;
&lt;li&gt;Branch Banking Portal&lt;/li&gt;
&lt;li&gt;Customer Support Portal&lt;/li&gt;
&lt;li&gt;Internal Banking Operations Dashboard
Frontend applications communicate with backend services through secured APIs.
2.2 Edge and API Management Layer
The edge layer acts as the entry point into the banking platform.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Important components include:&lt;/p&gt;

&lt;p&gt;AWS WAF&lt;/p&gt;

&lt;p&gt;Protects applications against common web attacks and malicious requests.&lt;/p&gt;

&lt;p&gt;Route 53&lt;/p&gt;

&lt;p&gt;Provides DNS resolution and directs customer requests to the application infrastructure.&lt;/p&gt;

&lt;p&gt;Application Load Balancer&lt;/p&gt;

&lt;p&gt;Distributes incoming traffic across available application endpoints.&lt;/p&gt;

&lt;p&gt;API Gateway&lt;/p&gt;

&lt;p&gt;Provides centralized API management capabilities.&lt;/p&gt;

&lt;p&gt;Responsibilities include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Request routing&lt;/li&gt;
&lt;li&gt;Authentication and authorization integration&lt;/li&gt;
&lt;li&gt;Rate limiting and throttling&lt;/li&gt;
&lt;li&gt;API versioning&lt;/li&gt;
&lt;li&gt;Request validation&lt;/li&gt;
&lt;li&gt;API monitoring
2.3 Microservices Layer
This layer contains the core banking business capabilities.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Each service implements a specific business responsibility.&lt;/p&gt;

&lt;p&gt;For example:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Account Service manages account information.&lt;/li&gt;
&lt;li&gt;Payment Service processes payment requests.&lt;/li&gt;
&lt;li&gt;Fund Transfer Service coordinates account-to-account transfers.&lt;/li&gt;
&lt;li&gt;Fraud Detection Service evaluates suspicious activities.&lt;/li&gt;
&lt;li&gt;Transaction Service manages transaction records and lifecycle.&lt;/li&gt;
&lt;li&gt;Notification Service sends transaction alerts.
2.4 Data and Messaging Layer
Different services may use different storage technologies based on their requirements.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Examples:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;PostgreSQL for transactional banking data.&lt;/li&gt;
&lt;li&gt;Oracle Database for enterprise banking systems.&lt;/li&gt;
&lt;li&gt;Redis for frequently accessed data and caching.&lt;/li&gt;
&lt;li&gt;DynamoDB for selected high-scale key-value workloads.&lt;/li&gt;
&lt;li&gt;Apache Kafka for asynchronous event-driven communication.
2.5 Infrastructure and Observability Layer
The infrastructure layer provides deployment, monitoring, security, and operational capabilities.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Examples:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;OpenShift / Kubernetes&lt;/li&gt;
&lt;li&gt;Docker&lt;/li&gt;
&lt;li&gt;Jenkins CI/CD&lt;/li&gt;
&lt;li&gt;Terraform&lt;/li&gt;
&lt;li&gt;Prometheus&lt;/li&gt;
&lt;li&gt;Grafana&lt;/li&gt;
&lt;li&gt;OpenTelemetry&lt;/li&gt;
&lt;li&gt;Splunk&lt;/li&gt;
&lt;li&gt;HashiCorp Vault&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fthek12thwc4evviouh46.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fthek12thwc4evviouh46.png" alt="BANKING PLATFORM MULTI LAYER ARCHITECTURE" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Designing Banking Microservices
Defining the right service boundaries is one of the most important decisions in microservices architecture.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Services should be designed around business capabilities rather than technical components.&lt;/p&gt;

&lt;p&gt;Let's understand some important banking services.&lt;br&gt;
3.1 Customer Service&lt;br&gt;
Responsible for managing customer-related information.&lt;/p&gt;

&lt;p&gt;Responsibilities:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Customer registration&lt;/li&gt;
&lt;li&gt;Customer profile management&lt;/li&gt;
&lt;li&gt;Customer information updates&lt;/li&gt;
&lt;li&gt;KYC status management&lt;/li&gt;
&lt;li&gt;Customer preferences
Example APIs:
POST   /api/customers
GET    /api/customers/{customerId}
PUT    /api/customers/{customerId}
GET    /api/customers/{customerId}/profile&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;3.2 Account Service&lt;br&gt;
Responsible for managing customer banking accounts.&lt;/p&gt;

&lt;p&gt;Responsibilities:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Account creation&lt;/li&gt;
&lt;li&gt;Account information&lt;/li&gt;
&lt;li&gt;Account status&lt;/li&gt;
&lt;li&gt;Account balance&lt;/li&gt;
&lt;li&gt;Account restrictions&lt;/li&gt;
&lt;li&gt;Account eligibility validation
Example APIs:
POST   /api/accounts
GET    /api/accounts/{accountId}
GET    /api/accounts/{accountId}/balance
GET    /api/customers/{customerId}/accounts&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The Account Service must enforce business rules around account ownership, account status, and transaction eligibility.&lt;br&gt;
3.3 Payment Service&lt;br&gt;
Responsible for processing payment requests.&lt;/p&gt;

&lt;p&gt;Responsibilities:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Payment initiation&lt;/li&gt;
&lt;li&gt;Payment validation&lt;/li&gt;
&lt;li&gt;Payment status management&lt;/li&gt;
&lt;li&gt;Payment authorization&lt;/li&gt;
&lt;li&gt;Payment failure handling&lt;/li&gt;
&lt;li&gt;Payment reconciliation integration
Example APIs:
POST   /api/payments
GET    /api/payments/{paymentId}
GET    /api/payments/{paymentId}/status&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Payment processing requires strong idempotency controls to prevent duplicate transactions.&lt;br&gt;
3.4 Fund Transfer Service&lt;br&gt;
Responsible for coordinating fund transfers between accounts.&lt;/p&gt;

&lt;p&gt;Responsibilities:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Validate source and destination accounts.&lt;/li&gt;
&lt;li&gt;Validate transfer limits.&lt;/li&gt;
&lt;li&gt;Check available funds.&lt;/li&gt;
&lt;li&gt;Coordinate debit and credit operations.&lt;/li&gt;
&lt;li&gt;Manage transaction status.&lt;/li&gt;
&lt;li&gt;Handle failed and pending transfers.
3.5 Fraud Detection Service
Responsible for identifying potentially suspicious banking activities.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Responsibilities:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Transaction risk assessment&lt;/li&gt;
&lt;li&gt;Unusual transaction detection&lt;/li&gt;
&lt;li&gt;Velocity checks&lt;/li&gt;
&lt;li&gt;Transaction pattern analysis&lt;/li&gt;
&lt;li&gt;Risk scoring&lt;/li&gt;
&lt;li&gt;Fraud alerts
Fraud detection can use rule-based processing, machine learning models, or a combination of both.
3.6 Notification Service
Responsible for communicating transaction-related updates.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Examples:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;SMS alerts&lt;/li&gt;
&lt;li&gt;Email notifications&lt;/li&gt;
&lt;li&gt;Push notifications&lt;/li&gt;
&lt;li&gt;Payment confirmation&lt;/li&gt;
&lt;li&gt;Failed transaction notifications&lt;/li&gt;
&lt;li&gt;Security alerts
The notification process should generally be asynchronous so that notification failures do not unnecessarily block the core transaction workflow.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fbrfffk1f7i2h5gveeipa.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fbrfffk1f7i2h5gveeipa.png" alt="BANKING MICROSERVICES BUSINESS CAPABILITY MAP" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Communication Between Microservices
Microservices need to communicate with each other to complete business workflows.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;There are two major communication approaches.&lt;br&gt;
4.1 Synchronous Communication&lt;br&gt;
Synchronous communication is used when a service requires an immediate response from another service.&lt;/p&gt;

&lt;p&gt;Common technologies:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;REST APIs&lt;/li&gt;
&lt;li&gt;Spring WebClient&lt;/li&gt;
&lt;li&gt;OpenFeign&lt;/li&gt;
&lt;li&gt;gRPC
Example:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;When a customer initiates a fund transfer:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Fund Transfer Service receives the request.&lt;/li&gt;
&lt;li&gt;It calls Account Service to validate account details.&lt;/li&gt;
&lt;li&gt;It calls Transaction Limit Service to validate transfer limits.&lt;/li&gt;
&lt;li&gt;It invokes Fraud Detection Service for risk evaluation.&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;It proceeds with the transfer workflow based on the results.&lt;br&gt;
Example using Spring WebClient:&lt;br&gt;
@Service&lt;br&gt;
public class AccountClient {&lt;/p&gt;

&lt;p&gt;private final WebClient webClient;&lt;/p&gt;

&lt;p&gt;public AccountClient(WebClient.Builder builder) {&lt;br&gt;
    this.webClient = builder&lt;br&gt;
            .baseUrl("&lt;a href="http://account-service%22" rel="noopener noreferrer"&gt;http://account-service"&lt;/a&gt;)&lt;br&gt;
            .build();&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;public Mono getAccount(&lt;br&gt;
        String accountId) {&lt;/p&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;return webClient.get()
        .uri("/api/accounts/{id}", accountId)
        .retrieve()
        .bodyToMono(AccountResponse.class);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;}&lt;br&gt;
}&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Synchronous communication is useful for immediate validation, but excessive service-to-service calls can increase latency and create runtime dependencies.&lt;br&gt;
4.2 Asynchronous Communication&lt;br&gt;
Asynchronous communication allows services to exchange events without waiting for immediate responses.&lt;/p&gt;

&lt;p&gt;Apache Kafka is commonly used for event-driven banking architectures.&lt;/p&gt;

&lt;p&gt;Example events:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;CustomerRegistered&lt;/li&gt;
&lt;li&gt;AccountCreated&lt;/li&gt;
&lt;li&gt;PaymentInitiated&lt;/li&gt;
&lt;li&gt;PaymentCompleted&lt;/li&gt;
&lt;li&gt;TransactionFailed&lt;/li&gt;
&lt;li&gt;FraudDetected&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;NotificationRequested&lt;br&gt;
Example Kafka producer:&lt;br&gt;
@Service&lt;br&gt;
public class PaymentEventPublisher {&lt;/p&gt;

&lt;p&gt;private final KafkaTemplate&lt;br&gt;
        kafkaTemplate;&lt;/p&gt;

&lt;p&gt;public PaymentEventPublisher(&lt;br&gt;
        KafkaTemplate kafkaTemplate) {&lt;br&gt;
    this.kafkaTemplate = kafkaTemplate;&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;public void publishPaymentEvent(&lt;br&gt;
        PaymentCompletedEvent event) {&lt;/p&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;kafkaTemplate.send(
        "payment-events",
        event.paymentId(),
        event
);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;}&lt;br&gt;
}&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Other services subscribe to the relevant events and execute their responsibilities independently.&lt;/p&gt;

&lt;p&gt;For example, Notification Service can consume PaymentCompleted events and send customer notifications.&lt;/p&gt;

&lt;p&gt;Important: Event-driven communication reduces direct runtime dependencies, but introduces challenges such as duplicate event delivery, eventual consistency, ordering, and retry handling.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F3v9h8wnhlmacxxwwkqp7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F3v9h8wnhlmacxxwwkqp7.png" alt="SYNCHRONOUS VS ASYNCHRONOUS BANKING COMMUNICATION" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Database Per Microservice Pattern
One of the fundamental principles of microservices architecture is database ownership.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Each microservice should own its data and expose access through well-defined APIs or events.&lt;/p&gt;

&lt;p&gt;For example:&lt;/p&gt;

&lt;p&gt;Customer Service&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Customer Database&lt;/li&gt;
&lt;li&gt;Customer profile&lt;/li&gt;
&lt;li&gt;KYC information
Account Service&lt;/li&gt;
&lt;li&gt;Account Database&lt;/li&gt;
&lt;li&gt;Account details&lt;/li&gt;
&lt;li&gt;Account status
Payment Service&lt;/li&gt;
&lt;li&gt;Payment Database&lt;/li&gt;
&lt;li&gt;Payment requests&lt;/li&gt;
&lt;li&gt;Payment lifecycle
Transaction Service&lt;/li&gt;
&lt;li&gt;Transaction Database&lt;/li&gt;
&lt;li&gt;Transaction history&lt;/li&gt;
&lt;li&gt;Transaction status
Fraud Detection Service&lt;/li&gt;
&lt;li&gt;Fraud Database&lt;/li&gt;
&lt;li&gt;Risk assessment&lt;/li&gt;
&lt;li&gt;Suspicious transaction records
Why is database ownership important?&lt;/li&gt;
&lt;li&gt;Services can evolve independently.&lt;/li&gt;
&lt;li&gt;Database schema changes are isolated.&lt;/li&gt;
&lt;li&gt;Services can choose suitable storage technologies.&lt;/li&gt;
&lt;li&gt;Teams can deploy independently.&lt;/li&gt;
&lt;li&gt;Data access is controlled through service contracts.
However, database-per-service does not mean every service must have a separate physical database server.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Multiple services can share database infrastructure while maintaining separate schemas, credentials, and ownership boundaries.&lt;br&gt;
Handling Data Consistency&lt;br&gt;
A banking application cannot simply ignore data consistency.&lt;/p&gt;

&lt;p&gt;For example, when transferring ₹10,000 from Account A to Account B, the system must ensure that the debit and credit operations are correctly coordinated.&lt;/p&gt;

&lt;p&gt;Distributed transactions across multiple databases are difficult to manage.&lt;/p&gt;

&lt;p&gt;Common architectural approaches include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Saga Pattern&lt;/li&gt;
&lt;li&gt;Transactional Outbox Pattern&lt;/li&gt;
&lt;li&gt;Eventual Consistency&lt;/li&gt;
&lt;li&gt;Idempotent Event Processing&lt;/li&gt;
&lt;li&gt;Reconciliation Jobs
For financial operations, the system must also maintain a reliable transaction history and auditable records.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fb0oeco5v9ghubqrl584i.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fb0oeco5v9ghubqrl584i.png" alt="DATABASE PER MICROSERVICE ARCHITECTURE" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Implementing a Banking Fund Transfer Workflow
Let's understand how an actual banking fund transfer can work.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Assume a customer wants to transfer ₹10,000 from Account A to Account B.&lt;/p&gt;

&lt;p&gt;The system must validate the transaction, prevent duplicate processing, update account balances safely, and maintain an auditable transaction record.&lt;br&gt;
Step-by-step workflow&lt;br&gt;
Step 1: Customer Initiates Transfer&lt;/p&gt;

&lt;p&gt;The customer submits a fund transfer request through the mobile banking application.&lt;br&gt;
POST /api/transfers&lt;br&gt;
Content-Type: application/json&lt;br&gt;
Idempotency-Key: TXN-123456&lt;/p&gt;

&lt;p&gt;Request:&lt;br&gt;
{&lt;br&gt;
  "sourceAccount": "ACC1001",&lt;br&gt;
  "destinationAccount": "ACC2001",&lt;br&gt;
  "amount": 10000,&lt;br&gt;
  "currency": "INR"&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;Step 2: API Gateway Validation&lt;/p&gt;

&lt;p&gt;API Gateway performs authentication, request validation, and routing.&lt;/p&gt;

&lt;p&gt;The request is forwarded to Fund Transfer Service.&lt;/p&gt;

&lt;p&gt;Step 3: Account Validation&lt;/p&gt;

&lt;p&gt;Fund Transfer Service validates:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Source account existence&lt;/li&gt;
&lt;li&gt;Destination account existence&lt;/li&gt;
&lt;li&gt;Account status&lt;/li&gt;
&lt;li&gt;Account ownership&lt;/li&gt;
&lt;li&gt;Transfer eligibility
Step 4: Transaction Limit Validation&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The system checks:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Daily transfer limits&lt;/li&gt;
&lt;li&gt;Per-transaction limits&lt;/li&gt;
&lt;li&gt;Customer-specific limits&lt;/li&gt;
&lt;li&gt;Regulatory restrictions
Step 5: Fraud Detection&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Fraud Detection Service evaluates the transaction using configured rules and risk scoring.&lt;/p&gt;

&lt;p&gt;If the transaction is suspicious, it may be rejected or sent for additional review.&lt;/p&gt;

&lt;p&gt;Step 6: Execute Fund Transfer&lt;/p&gt;

&lt;p&gt;The transfer workflow coordinates the debit and credit operations.&lt;/p&gt;

&lt;p&gt;For a distributed implementation, the Saga Pattern can manage the workflow across independently owned services.&lt;/p&gt;

&lt;p&gt;A successful transfer should guarantee that money is not permanently debited without the corresponding credit being completed.&lt;/p&gt;

&lt;p&gt;Step 7: Publish Transaction Event&lt;/p&gt;

&lt;p&gt;After successful completion, the system publishes a TransferCompleted event to Kafka.&lt;/p&gt;

&lt;p&gt;Step 8: Notification Processing&lt;/p&gt;

&lt;p&gt;Notification Service consumes the event and sends confirmation to the customer.&lt;/p&gt;

&lt;p&gt;Step 9: Transaction History&lt;/p&gt;

&lt;p&gt;Transaction Service updates or maintains the transaction history based on the established event and data ownership model.&lt;br&gt;
Important Design Considerations&lt;br&gt;
A real banking implementation must consider:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Idempotency keys&lt;/li&gt;
&lt;li&gt;Atomic debit and credit operations&lt;/li&gt;
&lt;li&gt;Double-entry accounting or ledger integration&lt;/li&gt;
&lt;li&gt;Optimistic or pessimistic locking&lt;/li&gt;
&lt;li&gt;Duplicate event handling&lt;/li&gt;
&lt;li&gt;Retry mechanisms&lt;/li&gt;
&lt;li&gt;Saga compensating transactions&lt;/li&gt;
&lt;li&gt;Reconciliation processes&lt;/li&gt;
&lt;li&gt;Audit logging
Important architectural consideration: For a financial transfer, do not implement debit and credit as two unrelated operations without a reliable consistency strategy. A dedicated ledger or core banking system should enforce financial invariants and maintain the authoritative financial records.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Frlo1y9555aa3tf71pdvt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Frlo1y9555aa3tf71pdvt.png" alt="END-TO-END BANKING FUND TRANSFER WORKFLOW" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Scalability and Performance Optimization
Banking applications must support varying traffic patterns.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;For example:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Salary credit dates&lt;/li&gt;
&lt;li&gt;Month-end transactions&lt;/li&gt;
&lt;li&gt;Festival shopping periods&lt;/li&gt;
&lt;li&gt;Tax payment deadlines&lt;/li&gt;
&lt;li&gt;Large-scale fund transfers
A scalable architecture must handle increasing traffic without affecting application stability.
7.1 Horizontal Scaling
Instead of increasing the resources of a single application instance, deploy multiple instances of each microservice.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For example:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Account Service: 5 replicas&lt;/li&gt;
&lt;li&gt;Payment Service: 8 replicas&lt;/li&gt;
&lt;li&gt;Customer Service: 3 replicas&lt;/li&gt;
&lt;li&gt;Notification Service: 4 replicas
These are illustrative replica counts, not production sizing recommendations.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Kubernetes or OpenShift can automatically scale workloads based on CPU, memory, or custom metrics.&lt;br&gt;
7.2 Horizontal Pod Autoscaler&lt;br&gt;
HPA automatically adjusts the number of application pods based on configured metrics.&lt;/p&gt;

&lt;p&gt;Example Kubernetes configuration:&lt;br&gt;
apiVersion: autoscaling/v2&lt;br&gt;
kind: HorizontalPodAutoscaler&lt;/p&gt;

&lt;p&gt;metadata:&lt;br&gt;
  name: payment-service-hpa&lt;/p&gt;

&lt;p&gt;spec:&lt;br&gt;
  scaleTargetRef:&lt;br&gt;
    apiVersion: apps/v1&lt;br&gt;
    kind: Deployment&lt;br&gt;
    name: payment-service&lt;/p&gt;

&lt;p&gt;minReplicas: 3&lt;br&gt;
  maxReplicas: 15&lt;/p&gt;

&lt;p&gt;metrics:&lt;br&gt;
    - type: Resource&lt;br&gt;
      resource:&lt;br&gt;
        name: cpu&lt;br&gt;
        target:&lt;br&gt;
          type: Utilization&lt;br&gt;
          averageUtilization: 70&lt;/p&gt;

&lt;p&gt;When average CPU utilization increases beyond the target, Kubernetes can scale the number of pods.&lt;/p&gt;

&lt;p&gt;However, CPU-based scaling alone may not be sufficient for banking applications.&lt;/p&gt;

&lt;p&gt;Additional metrics to consider:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Request rate&lt;/li&gt;
&lt;li&gt;API response time&lt;/li&gt;
&lt;li&gt;Kafka consumer lag&lt;/li&gt;
&lt;li&gt;Active requests&lt;/li&gt;
&lt;li&gt;Queue depth&lt;/li&gt;
&lt;li&gt;Database connection utilization
7.3 Redis Caching
Redis can reduce repeated database access for frequently requested data.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Examples:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Customer profile information&lt;/li&gt;
&lt;li&gt;Branch information&lt;/li&gt;
&lt;li&gt;Product configuration&lt;/li&gt;
&lt;li&gt;Reference data&lt;/li&gt;
&lt;li&gt;Non-authoritative account display information
However, financial transaction decisions must always use authoritative and sufficiently fresh data.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Caching account balances requires careful consistency and invalidation strategies.&lt;br&gt;
7.4 Database Optimization&lt;br&gt;
Database performance is critical for banking applications.&lt;/p&gt;

&lt;p&gt;Important techniques:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Proper indexing&lt;/li&gt;
&lt;li&gt;Query optimization&lt;/li&gt;
&lt;li&gt;Connection pooling&lt;/li&gt;
&lt;li&gt;Read replicas where appropriate&lt;/li&gt;
&lt;li&gt;Partitioning large transaction tables&lt;/li&gt;
&lt;li&gt;Batch processing&lt;/li&gt;
&lt;li&gt;Archival strategies
7.5 Kafka Partitioning
Kafka supports parallel event processing through partitions.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For example, a payment-events topic can have multiple partitions.&lt;/p&gt;

&lt;p&gt;Using a suitable key, such as account ID or aggregate ID, can help preserve ordering for related events within a partition.&lt;/p&gt;

&lt;p&gt;The partitioning strategy should consider ordering requirements, traffic distribution, and consumer parallelism.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F1bgd4k65awb7se30j49i.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F1bgd4k65awb7se30j49i.png" alt="BANKING MICROSERVICES SCALABILITY ARCHITECTURE" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Resilience and Fault Tolerance
In distributed systems, service failures are inevitable.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A Payment Service might become unavailable, a database might experience increased latency, or a Kafka consumer might stop processing events.&lt;/p&gt;

&lt;p&gt;A scalable banking architecture must handle these failures gracefully.&lt;br&gt;
8.1 Circuit Breaker Pattern&lt;br&gt;
Prevents repeated calls to an unhealthy downstream service.&lt;/p&gt;

&lt;p&gt;For example, if Fraud Detection Service is unavailable, the Fund Transfer Service should not continuously send requests and overload it.&lt;/p&gt;

&lt;p&gt;Resilience4j provides circuit breaker capabilities in Spring Boot applications.&lt;br&gt;
8.2 Retry Pattern&lt;br&gt;
Retries transient failures such as temporary network issues.&lt;/p&gt;

&lt;p&gt;However, retrying a financial operation without idempotency can cause duplicate transactions.&lt;/p&gt;

&lt;p&gt;Use bounded retries, backoff, jitter, and idempotency controls.&lt;br&gt;
8.3 Timeout Pattern&lt;br&gt;
Every remote service call should have an appropriate timeout.&lt;/p&gt;

&lt;p&gt;Without timeouts, application threads and resources can remain occupied waiting for unavailable services.&lt;br&gt;
8.4 Bulkhead Pattern&lt;br&gt;
Separates resources to prevent failures in one area from affecting the entire application.&lt;/p&gt;

&lt;p&gt;For example, payment processing should not consume all available threads required by account inquiry operations.&lt;br&gt;
8.5 Dead Letter Queue&lt;br&gt;
Messages that repeatedly fail processing can be moved to a dead letter topic for investigation and controlled reprocessing.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F4hcb9jhqrnrnzso9xq9d.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F4hcb9jhqrnrnzso9xq9d.png" alt="BANKING MICROSERVICES RESILIENCE ARCHITECTURE" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Security in Banking Microservices
Security is one of the most important non-functional requirements for banking applications.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The architecture must protect customer information, financial transactions, APIs, and internal service communication.&lt;br&gt;
Authentication and Authorization&lt;br&gt;
Use OAuth 2.0 and OpenID Connect with an appropriate identity provider.&lt;/p&gt;

&lt;p&gt;JWT tokens can carry authenticated user identity and authorization claims.&lt;br&gt;
Role-Based Access Control&lt;br&gt;
Different users should have different access privileges.&lt;/p&gt;

&lt;p&gt;Examples:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Customer&lt;/li&gt;
&lt;li&gt;Bank Employee&lt;/li&gt;
&lt;li&gt;Branch Manager&lt;/li&gt;
&lt;li&gt;Banking Administrator&lt;/li&gt;
&lt;li&gt;Audit User
Mutual TLS
mTLS provides certificate-based authentication between communicating services.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;It helps ensure that only trusted services can establish secure connections.&lt;br&gt;
Secrets Management&lt;br&gt;
Never hardcode database passwords, API keys, or certificates.&lt;/p&gt;

&lt;p&gt;Use a centralized secrets management platform such as HashiCorp Vault.&lt;br&gt;
Encryption&lt;br&gt;
Apply encryption in transit using TLS and encryption at rest using appropriate database and storage encryption mechanisms.&lt;br&gt;
Audit Logging&lt;br&gt;
Maintain traceable records of sensitive operations, including:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Transaction initiation&lt;/li&gt;
&lt;li&gt;Payment authorization&lt;/li&gt;
&lt;li&gt;Account modifications&lt;/li&gt;
&lt;li&gt;Administrative actions&lt;/li&gt;
&lt;li&gt;Failed authentication attempts
Sensitive information such as passwords, authentication tokens, and full payment credentials must not appear in application logs.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fh6suwx317qisagb6avgr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fh6suwx317qisagb6avgr.png" alt="ENTERPRISE BANKING MICROSERVICES SECURITY ARCHITECTURE" width="800" height="451"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Monitoring and Observability
In a distributed microservices environment, troubleshooting is more complex than in a monolithic application.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A single fund transfer may involve multiple services, databases, and Kafka events.&lt;/p&gt;

&lt;p&gt;Observability helps engineers understand application health and identify performance bottlenecks.&lt;br&gt;
Metrics&lt;br&gt;
Prometheus can collect metrics such as:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Request count&lt;/li&gt;
&lt;li&gt;API latency&lt;/li&gt;
&lt;li&gt;Error percentage&lt;/li&gt;
&lt;li&gt;JVM memory usage&lt;/li&gt;
&lt;li&gt;CPU utilization&lt;/li&gt;
&lt;li&gt;Thread pool utilization&lt;/li&gt;
&lt;li&gt;Kafka consumer lag&lt;/li&gt;
&lt;li&gt;Database connection pool usage
Grafana can visualize these metrics through dashboards.
Distributed Tracing
OpenTelemetry helps trace requests across multiple services.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For example:&lt;br&gt;
Mobile Banking&lt;br&gt;
      |&lt;br&gt;
      v&lt;br&gt;
API Gateway&lt;br&gt;
      |&lt;br&gt;
      v&lt;br&gt;
Fund Transfer Service&lt;br&gt;
      |&lt;br&gt;
      +------&amp;gt; Account Service&lt;br&gt;
      |&lt;br&gt;
      +------&amp;gt; Fraud Detection&lt;br&gt;
      |&lt;br&gt;
      +------&amp;gt; Payment/Ledger Service&lt;br&gt;
      |&lt;br&gt;
      v&lt;br&gt;
Kafka&lt;br&gt;
      |&lt;br&gt;
      v&lt;br&gt;
Notification Service&lt;/p&gt;

&lt;p&gt;A distributed trace helps identify which service introduced latency or failed during the transaction.&lt;br&gt;
Centralized Logging&lt;br&gt;
Splunk or another centralized logging platform can aggregate logs from different microservices.&lt;/p&gt;

&lt;p&gt;Use correlation IDs and trace IDs to connect related log entries.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fvh51pxywrn6lx58ui04q.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fvh51pxywrn6lx58ui04q.png" alt="BANKING MICROSERVICES OBSERVABILITY ARCHITECTURE" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Deployment Architecture Using OpenShift/Kubernetes
A banking microservices platform should support automated, repeatable, and reliable deployments.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A typical CI/CD pipeline can look like this:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Developer pushes code to Git.&lt;/li&gt;
&lt;li&gt;Jenkins pipeline starts.&lt;/li&gt;
&lt;li&gt;Maven compiles the application.&lt;/li&gt;
&lt;li&gt;Unit and integration tests execute.&lt;/li&gt;
&lt;li&gt;SonarQube performs static code analysis.&lt;/li&gt;
&lt;li&gt;Application artifact is packaged.&lt;/li&gt;
&lt;li&gt;Docker image is created.&lt;/li&gt;
&lt;li&gt;Image is pushed to a container registry.&lt;/li&gt;
&lt;li&gt;Deployment is performed on OpenShift/Kubernetes.&lt;/li&gt;
&lt;li&gt;Health checks and monitoring validate the deployment.
Important deployment strategies include:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Rolling Deployment&lt;/p&gt;

&lt;p&gt;Gradually replaces old application instances with new instances.&lt;/p&gt;

&lt;p&gt;Blue-Green Deployment&lt;/p&gt;

&lt;p&gt;Maintains two environments and switches traffic after validation.&lt;/p&gt;

&lt;p&gt;Canary Deployment&lt;/p&gt;

&lt;p&gt;Routes a small percentage of traffic to a new version before gradually increasing exposure.&lt;/p&gt;

&lt;p&gt;For banking applications, deployments should also include database migration compatibility, rollback planning, smoke testing, and transaction integrity validation.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F9s0n46nv6nilgkd5wja9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F9s0n46nv6nilgkd5wja9.png" alt="BANKING MICROSERVICES CICD DEPLOYMENT ARCHITECTURE" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Important Non-Functional Requirements (NFRs)
Designing banking microservices is not just about implementing business functionality.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A Solution Architect must define and validate non-functional requirements before finalizing the architecture.&lt;/p&gt;

&lt;p&gt;Important NFRs include:&lt;/p&gt;

&lt;p&gt;Availability&lt;/p&gt;

&lt;p&gt;The system should remain available during infrastructure and application failures.&lt;/p&gt;

&lt;p&gt;Scalability&lt;/p&gt;

&lt;p&gt;The platform should support increasing transaction volumes through horizontal scaling.&lt;/p&gt;

&lt;p&gt;Performance&lt;/p&gt;

&lt;p&gt;APIs should meet defined response-time objectives under expected and peak workloads.&lt;/p&gt;

&lt;p&gt;Reliability&lt;/p&gt;

&lt;p&gt;Financial transactions must be processed correctly without losing or duplicating money movements.&lt;/p&gt;

&lt;p&gt;Security&lt;/p&gt;

&lt;p&gt;Customer information and financial transactions must be protected against unauthorized access.&lt;/p&gt;

&lt;p&gt;Consistency&lt;/p&gt;

&lt;p&gt;Financial records and account balances must follow clearly defined consistency guarantees.&lt;/p&gt;

&lt;p&gt;Disaster Recovery&lt;/p&gt;

&lt;p&gt;The architecture should define Recovery Time Objective (RTO) and Recovery Point Objective (RPO).&lt;/p&gt;

&lt;p&gt;Observability&lt;/p&gt;

&lt;p&gt;The platform should provide sufficient metrics, logs, and traces for operational troubleshooting.&lt;br&gt;
Example NFR targets&lt;br&gt;
The following are illustrative starting points for architecture discussions, not universal banking standards.&lt;br&gt;
NFR Illustrative Target&lt;br&gt;
Availability    99.95%&lt;br&gt;
API response time   p95 below 300 ms for selected read APIs&lt;br&gt;
Throughput  2,000 TPS&lt;br&gt;
Recovery Time Objective 30 minutes&lt;br&gt;
Recovery Point Objective    5 minutes&lt;br&gt;
Horizontal scaling  Automatic based on workload&lt;br&gt;
Security    TLS, OAuth 2.0, mTLS&lt;br&gt;
Monitoring  Metrics, logs, distributed tracing&lt;/p&gt;

&lt;p&gt;Actual targets should be derived from business SLAs, transaction characteristics, regulatory requirements, workload testing, and cost constraints.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Challenges in Banking Microservices Architecture
Although microservices provide flexibility, they also introduce architectural complexity.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Some common challenges include:&lt;/p&gt;

&lt;p&gt;Distributed Transactions&lt;/p&gt;

&lt;p&gt;Maintaining financial consistency across multiple services requires careful transaction coordination and ledger design.&lt;/p&gt;

&lt;p&gt;Service Dependencies&lt;/p&gt;

&lt;p&gt;Too many synchronous dependencies can increase latency and create cascading failures.&lt;/p&gt;

&lt;p&gt;Eventual Consistency&lt;/p&gt;

&lt;p&gt;Different services may temporarily hold different views of business data.&lt;/p&gt;

&lt;p&gt;Operational Complexity&lt;/p&gt;

&lt;p&gt;Managing multiple services, deployments, configurations, and monitoring systems requires strong DevOps practices.&lt;/p&gt;

&lt;p&gt;Data Duplication&lt;/p&gt;

&lt;p&gt;Different services may maintain their own representations of business information. These copies must be managed through reliable synchronization strategies.&lt;/p&gt;

&lt;p&gt;Security Management&lt;/p&gt;

&lt;p&gt;Securing service-to-service communication, managing certificates, and controlling access across distributed services require centralized governance.&lt;/p&gt;

&lt;p&gt;Debugging&lt;/p&gt;

&lt;p&gt;Tracing a business transaction across multiple services requires correlation IDs and distributed tracing.&lt;/p&gt;

&lt;p&gt;A successful architecture must address these challenges through clear service boundaries, strong engineering standards, and operational governance.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Best Practices for Designing Enterprise Banking Microservices
When designing a production-grade banking platform, consider the following principles:&lt;/li&gt;
&lt;li&gt;Design microservices around business capabilities and bounded contexts.&lt;/li&gt;
&lt;li&gt;Maintain independent service ownership and database boundaries.&lt;/li&gt;
&lt;li&gt;Use synchronous communication only when an immediate response is required.&lt;/li&gt;
&lt;li&gt;Use Kafka for appropriate asynchronous business events.&lt;/li&gt;
&lt;li&gt;Implement idempotency for financial operations.&lt;/li&gt;
&lt;li&gt;Use Saga and Outbox patterns where distributed workflows require them.&lt;/li&gt;
&lt;li&gt;Protect critical financial operations with strong consistency guarantees.&lt;/li&gt;
&lt;li&gt;Implement circuit breakers, timeouts, retries, and bulkheads.&lt;/li&gt;
&lt;li&gt;Use Redis carefully for frequently accessed non-authoritative data.&lt;/li&gt;
&lt;li&gt;Implement horizontal scaling based on workload metrics.&lt;/li&gt;
&lt;li&gt;Secure APIs and internal service communication.&lt;/li&gt;
&lt;li&gt;Implement centralized observability and audit logging.&lt;/li&gt;
&lt;li&gt;Automate deployments through CI/CD pipelines.&lt;/li&gt;
&lt;li&gt;Define NFRs and validate them through performance and failure testing.&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Maintain a reliable reconciliation and disaster recovery strategy.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Conclusion&lt;br&gt;
Designing scalable banking microservices requires more than splitting a monolithic application into smaller services.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;It requires understanding business capabilities, defining clear service boundaries, choosing the right communication patterns, managing distributed data consistency, and building resilient infrastructure.&lt;/p&gt;

&lt;p&gt;Technologies such as Java 21, Spring Boot, Apache Kafka, Redis, PostgreSQL, OpenShift, and Kubernetes provide a strong foundation for building modern banking platforms.&lt;/p&gt;

&lt;p&gt;However, technology alone does not guarantee a successful architecture.&lt;/p&gt;

&lt;p&gt;The real responsibility of a Solution Architect is to ensure that the architecture satisfies business requirements while meeting availability, scalability, performance, security, reliability, and regulatory expectations.&lt;/p&gt;

&lt;p&gt;A well-designed banking architecture is not just scalable. It must also be secure, resilient, consistent, observable, and operationally manageable.&lt;/p&gt;

&lt;p&gt;Author: Ram The Architect (RTA)&lt;/p&gt;

&lt;p&gt;Follow me for more practical insights on Java 21 | Spring Boot | Microservices | Apache Kafka | AWS | System Design | GenAI&lt;/p&gt;

&lt;p&gt;Connect with me:&lt;/p&gt;

&lt;p&gt;GitHub: &lt;a href="https://github.com/Ramu-fsd" rel="noopener noreferrer"&gt;https://github.com/Ramu-fsd&lt;/a&gt;&lt;br&gt;
LinkedIn: &lt;a href="https://www.linkedin.com/in/ramuboya/" rel="noopener noreferrer"&gt;https://www.linkedin.com/in/ramuboya/&lt;/a&gt;&lt;br&gt;
Facebook: &lt;a href="https://www.facebook.com/RamTheArchitect" rel="noopener noreferrer"&gt;https://www.facebook.com/RamTheArchitect&lt;/a&gt;&lt;br&gt;
Medium: &lt;a href="https://medium.com/@ramthearchitect" rel="noopener noreferrer"&gt;https://medium.com/@ramthearchitect&lt;/a&gt;&lt;/p&gt;

</description>
      <category>microservices</category>
      <category>systemdesign</category>
      <category>java21</category>
      <category>bankingarchitecture</category>
    </item>
    <item>
      <title>RAG Evaluation: Faithfulness, Relevance, Retrieval Quality and Grounding</title>
      <dc:creator>Ramanjaneyulu Boya</dc:creator>
      <pubDate>Sun, 29 Nov 2026 14:10:03 +0000</pubDate>
      <link>https://dev.to/ramthearchitect/rag-evaluation-faithfulness-relevance-retrieval-quality-and-grounding-30n4</link>
      <guid>https://dev.to/ramthearchitect/rag-evaluation-faithfulness-relevance-retrieval-quality-and-grounding-30n4</guid>
      <description>&lt;p&gt;Building a Retrieval-Augmented Generation (RAG) application is not just about connecting an LLM to a vector database.&lt;/p&gt;

&lt;p&gt;A RAG application may successfully retrieve documents, generate a fluent response, and still provide incorrect or misleading information.&lt;/p&gt;

&lt;p&gt;For enterprise applications, especially in banking, payments, insurance, and healthcare, &lt;strong&gt;a confident but unsupported answer can be more dangerous than no answer at all.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This is why RAG evaluation is a critical part of production AI engineering.&lt;/p&gt;

&lt;p&gt;In this article, we will explore four important dimensions of RAG evaluation:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Faithfulness&lt;/li&gt;
&lt;li&gt;Answer Relevance&lt;/li&gt;
&lt;li&gt;Retrieval Quality&lt;/li&gt;
&lt;li&gt;Grounding&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We will also understand how to evaluate a RAG application using a practical fintech use case.&lt;/p&gt;




&lt;h2&gt;
  
  
  1. Why RAG Evaluation Matters
&lt;/h2&gt;

&lt;p&gt;A typical RAG pipeline consists of the following steps:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Receive a user query.&lt;/li&gt;
&lt;li&gt;Convert the query into an embedding.&lt;/li&gt;
&lt;li&gt;Retrieve relevant documents from a vector database.&lt;/li&gt;
&lt;li&gt;Build a prompt using the retrieved context.&lt;/li&gt;
&lt;li&gt;Send the prompt to an LLM.&lt;/li&gt;
&lt;li&gt;Generate the final answer.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F0ch1jbafwgkoy2nrrxg7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F0ch1jbafwgkoy2nrrxg7.png" alt="RAG EVALUATION PIPELINE" width="800" height="410"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The challenge is that every stage can introduce errors.&lt;/p&gt;

&lt;p&gt;For example:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The retriever may return irrelevant documents.&lt;/li&gt;
&lt;li&gt;The correct document may not be retrieved.&lt;/li&gt;
&lt;li&gt;The LLM may ignore the retrieved context.&lt;/li&gt;
&lt;li&gt;The generated answer may introduce unsupported facts.&lt;/li&gt;
&lt;li&gt;The answer may be technically correct but fail to address the user's question.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Traditional application testing cannot fully validate these behaviors.&lt;/p&gt;

&lt;p&gt;We need a dedicated evaluation strategy.&lt;/p&gt;




&lt;h2&gt;
  
  
  2. Faithfulness: Is the Answer Supported by the Context?
&lt;/h2&gt;

&lt;p&gt;Faithfulness measures whether the generated answer is supported by the retrieved context.&lt;/p&gt;

&lt;p&gt;It helps identify hallucinations introduced by the LLM.&lt;/p&gt;

&lt;h3&gt;
  
  
  Example
&lt;/h3&gt;

&lt;p&gt;User query:&lt;/p&gt;

&lt;p&gt;"What is the maximum daily transfer limit for a premium banking customer?"&lt;/p&gt;

&lt;p&gt;Retrieved context:&lt;/p&gt;

&lt;p&gt;"Premium banking customers can transfer up to ₹5,00,000 per day through the mobile banking application."&lt;/p&gt;

&lt;p&gt;Generated answer:&lt;/p&gt;

&lt;p&gt;"Premium banking customers can transfer up to ₹5,00,000 per day through mobile banking."&lt;/p&gt;

&lt;p&gt;This answer is faithful because it is supported by the retrieved context.&lt;/p&gt;

&lt;p&gt;Now consider another answer:&lt;/p&gt;

&lt;p&gt;"Premium banking customers can transfer up to ₹10,00,000 per day through mobile banking."&lt;/p&gt;

&lt;p&gt;The answer sounds reasonable, but the retrieved context does not support the ₹10,00,000 limit.&lt;/p&gt;

&lt;p&gt;This is a faithfulness failure.&lt;/p&gt;

&lt;h3&gt;
  
  
  How to evaluate faithfulness
&lt;/h3&gt;

&lt;p&gt;A common approach is to:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Extract factual claims from the generated answer.&lt;/li&gt;
&lt;li&gt;Check whether each claim is supported by the retrieved context.&lt;/li&gt;
&lt;li&gt;Calculate the proportion of supported claims.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A simplified formula:&lt;/p&gt;

&lt;p&gt;Faithfulness = Supported Claims / Total Claims&lt;/p&gt;

&lt;p&gt;For example, if an answer contains 5 factual claims and 4 are supported:&lt;/p&gt;

&lt;p&gt;Faithfulness = 4 / 5 = 0.80&lt;/p&gt;

&lt;p&gt;A score of 1.0 indicates that all evaluated claims are supported by the context.&lt;/p&gt;

&lt;p&gt;However, faithfulness does not guarantee that the retrieved context itself is correct.&lt;/p&gt;




&lt;h2&gt;
  
  
  3. Answer Relevance: Does the Answer Address the Question?
&lt;/h2&gt;

&lt;p&gt;Answer relevance measures how directly the generated answer responds to the user's query.&lt;/p&gt;

&lt;p&gt;An answer can be factually correct and faithful but still irrelevant.&lt;/p&gt;

&lt;h3&gt;
  
  
  Example
&lt;/h3&gt;

&lt;p&gt;User query:&lt;/p&gt;

&lt;p&gt;"What is the daily transfer limit for premium customers?"&lt;/p&gt;

&lt;p&gt;Generated answer:&lt;/p&gt;

&lt;p&gt;"Premium banking customers receive personalized banking services, priority customer support, and access to exclusive financial products."&lt;/p&gt;

&lt;p&gt;The answer may be factually correct, but it does not answer the transfer-limit question.&lt;/p&gt;

&lt;p&gt;This is an answer relevance failure.&lt;/p&gt;

&lt;p&gt;A good response should directly address the requested information:&lt;/p&gt;

&lt;p&gt;"Premium customers can transfer up to ₹5,00,000 per day through mobile banking."&lt;/p&gt;

&lt;h3&gt;
  
  
  Important distinction
&lt;/h3&gt;

&lt;p&gt;Faithfulness and relevance measure different things.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Faithfulness: Is the answer supported by the context?&lt;/li&gt;
&lt;li&gt;Relevance: Does the answer address the user's question?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A response can score high on one and low on the other.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fwp5l1f80bk6weqqbmouk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fwp5l1f80bk6weqqbmouk.png" alt="FAITHFULNESS VS ANSWER RELEVANCE" width="800" height="533"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This distinction is particularly important when evaluating enterprise AI assistants.&lt;/p&gt;




&lt;h2&gt;
  
  
  4. Retrieval Quality: Did We Retrieve the Right Documents?
&lt;/h2&gt;

&lt;p&gt;Retrieval quality evaluates the performance of the retriever before the LLM generates an answer.&lt;/p&gt;

&lt;p&gt;Even a powerful LLM cannot reliably answer a question if the required information is missing from the retrieved context.&lt;/p&gt;

&lt;p&gt;Consider a banking knowledge base containing:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Customer onboarding policies&lt;/li&gt;
&lt;li&gt;Payment processing rules&lt;/li&gt;
&lt;li&gt;Transaction limits&lt;/li&gt;
&lt;li&gt;Fraud detection guidelines&lt;/li&gt;
&lt;li&gt;Loan eligibility criteria&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A query about transaction limits should retrieve the correct transaction-limit policy, not a general banking document.&lt;/p&gt;

&lt;h3&gt;
  
  
  Precision@K
&lt;/h3&gt;

&lt;p&gt;Precision@K measures how many of the top K retrieved documents are relevant.&lt;/p&gt;

&lt;p&gt;Precision@K = Relevant Retrieved Documents / K&lt;/p&gt;

&lt;p&gt;Suppose the retriever returns 5 documents, and 4 are relevant.&lt;/p&gt;

&lt;p&gt;Precision@5 = 4 / 5 = 0.80&lt;/p&gt;

&lt;p&gt;This tells us that 80% of the retrieved documents are relevant.&lt;/p&gt;

&lt;h3&gt;
  
  
  Recall@K
&lt;/h3&gt;

&lt;p&gt;Recall@K measures how many of the known relevant documents were retrieved in the top K results.&lt;/p&gt;

&lt;p&gt;Recall@K = Relevant Retrieved Documents Retrieved / Total Relevant Documents&lt;/p&gt;

&lt;p&gt;Suppose there are 10 relevant documents in the evaluation dataset, and the retriever finds 7.&lt;/p&gt;

&lt;p&gt;Recall@K = 7 / 10 = 0.70&lt;/p&gt;

&lt;p&gt;This means the retriever found 70% of the relevant documents.&lt;/p&gt;

&lt;h3&gt;
  
  
  Why both metrics matter
&lt;/h3&gt;

&lt;p&gt;High precision means the retrieved context contains fewer irrelevant documents.&lt;/p&gt;

&lt;p&gt;High recall means the retriever is finding more of the information needed to answer the question.&lt;/p&gt;

&lt;p&gt;For enterprise RAG systems, we often need to balance both.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fj25m5vn45nm1t9i0ijvs.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fj25m5vn45nm1t9i0ijvs.png" alt="RETRIEVAL PRECISION AND RECALL" width="800" height="410"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Other useful retrieval metrics include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Mean Reciprocal Rank (MRR)&lt;/li&gt;
&lt;li&gt;Normalized Discounted Cumulative Gain (NDCG)&lt;/li&gt;
&lt;li&gt;Hit Rate@K&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;MRR evaluates how highly the first relevant result is ranked.&lt;/p&gt;

&lt;p&gt;NDCG considers both relevance and ranking position, making it useful when highly relevant documents should appear near the top.&lt;/p&gt;




&lt;h2&gt;
  
  
  5. Grounding: Can We Trace the Answer to Reliable Sources?
&lt;/h2&gt;

&lt;p&gt;Grounding evaluates whether the generated response is anchored in trustworthy evidence.&lt;/p&gt;

&lt;p&gt;In a RAG application, grounding is more than retrieving a document.&lt;/p&gt;

&lt;p&gt;The answer should be traceable to the correct source, such as:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;An approved banking policy&lt;/li&gt;
&lt;li&gt;An official product document&lt;/li&gt;
&lt;li&gt;A customer-specific record&lt;/li&gt;
&lt;li&gt;A regulatory guideline&lt;/li&gt;
&lt;li&gt;An authorized internal knowledge article&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Example
&lt;/h3&gt;

&lt;p&gt;User query:&lt;/p&gt;

&lt;p&gt;"Can I reverse a completed payment?"&lt;/p&gt;

&lt;p&gt;Generated answer:&lt;/p&gt;

&lt;p&gt;"Completed payments cannot be directly reversed through the mobile application. Customers must raise a dispute through the approved support process."&lt;/p&gt;

&lt;p&gt;A grounded response should reference the approved payment-reversal policy that supports this statement.&lt;/p&gt;

&lt;p&gt;For enterprise applications, grounding should ideally include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Source document ID&lt;/li&gt;
&lt;li&gt;Document version&lt;/li&gt;
&lt;li&gt;Relevant page or section&lt;/li&gt;
&lt;li&gt;Retrieval timestamp&lt;/li&gt;
&lt;li&gt;Access-control validation&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fp6n960c8m0577iy8u4qb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fp6n960c8m0577iy8u4qb.png" alt="GROUNDED ANSWER WITH SOURCE CITATIONS" width="800" height="409"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Grounding vs Faithfulness
&lt;/h3&gt;

&lt;p&gt;These concepts are closely related but not identical.&lt;/p&gt;

&lt;p&gt;Faithfulness asks:&lt;/p&gt;

&lt;p&gt;"Does the answer follow the retrieved context?"&lt;/p&gt;

&lt;p&gt;Grounding asks:&lt;/p&gt;

&lt;p&gt;"Is the answer supported by reliable, traceable evidence?"&lt;/p&gt;

&lt;p&gt;An answer could be faithful to an outdated policy document but still be incorrectly grounded in the current business context.&lt;/p&gt;

&lt;p&gt;This is why document freshness, versioning, and source authority are important.&lt;/p&gt;




&lt;h2&gt;
  
  
  6. Putting the Metrics Together
&lt;/h2&gt;

&lt;p&gt;Let's evaluate a hypothetical banking RAG application.&lt;/p&gt;

&lt;p&gt;User query:&lt;/p&gt;

&lt;p&gt;"What is the daily transfer limit for premium customers?"&lt;/p&gt;

&lt;p&gt;Expected answer:&lt;/p&gt;

&lt;p&gt;"Premium customers can transfer up to ₹5,00,000 per day through mobile banking."&lt;/p&gt;

&lt;p&gt;Retrieved documents:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Document 1: Premium customer transaction limits&lt;/li&gt;
&lt;li&gt;Document 2: Mobile banking security policy&lt;/li&gt;
&lt;li&gt;Document 3: General banking services&lt;/li&gt;
&lt;li&gt;Document 4: Premium customer benefits&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Generated answer:&lt;/p&gt;

&lt;p&gt;"Premium customers can transfer up to ₹5,00,000 per day through mobile banking. Transfers above this limit require additional authorization."&lt;/p&gt;

&lt;p&gt;Evaluation:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Metric&lt;/th&gt;
&lt;th&gt;Result&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Faithfulness&lt;/td&gt;
&lt;td&gt;High, if both claims are supported&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Answer Relevance&lt;/td&gt;
&lt;td&gt;High&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Retrieval Precision@4&lt;/td&gt;
&lt;td&gt;Depends on which documents are relevant&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Retrieval Recall@4&lt;/td&gt;
&lt;td&gt;Depends on the known relevant document set&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Grounding&lt;/td&gt;
&lt;td&gt;High, if supported by current approved policies&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Notice that the second sentence about additional authorization must also be verified.&lt;/p&gt;

&lt;p&gt;A correct first sentence does not automatically make the entire answer faithful.&lt;/p&gt;




&lt;h2&gt;
  
  
  7. Building a RAG Evaluation Dataset
&lt;/h2&gt;

&lt;p&gt;A reliable evaluation process starts with a curated dataset.&lt;/p&gt;

&lt;p&gt;For each test case, maintain:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;User query&lt;/li&gt;
&lt;li&gt;Expected answer&lt;/li&gt;
&lt;li&gt;Relevant document IDs&lt;/li&gt;
&lt;li&gt;Reference answer or key facts&lt;/li&gt;
&lt;li&gt;Retrieved context&lt;/li&gt;
&lt;li&gt;Generated answer&lt;/li&gt;
&lt;li&gt;Evaluation scores&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Example test cases:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Query&lt;/th&gt;
&lt;th&gt;Expected behavior&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;What is the daily transfer limit?&lt;/td&gt;
&lt;td&gt;Return the approved limit&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;How can I reverse a completed payment?&lt;/td&gt;
&lt;td&gt;Explain the approved dispute process&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;What documents are required for KYC?&lt;/td&gt;
&lt;td&gt;List required documents&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;What is the loan eligibility criteria?&lt;/td&gt;
&lt;td&gt;Retrieve the correct loan policy&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;What is the current policy version?&lt;/td&gt;
&lt;td&gt;Identify the latest approved version&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Include difficult cases such as ambiguous queries, missing information, conflicting documents, outdated policies, and questions that should not be answered.&lt;/p&gt;

&lt;p&gt;A production-ready RAG system must also know when to say:&lt;/p&gt;

&lt;p&gt;"I couldn't find sufficient information in the approved sources to answer this question."&lt;/p&gt;




&lt;h2&gt;
  
  
  8. Evaluating RAG in a Java Spring AI Application
&lt;/h2&gt;

&lt;p&gt;For Java backend developers, RAG evaluation can be integrated into the application testing and CI/CD process.&lt;/p&gt;

&lt;p&gt;A typical architecture:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ff5qwlv180b2yr4b0oo60.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ff5qwlv180b2yr4b0oo60.png" alt="JAVA SPRING AI RAG EVALUATION ARCHITECTURE" width="800" height="409"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;A practical implementation can include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Spring AI for retrieval and model orchestration&lt;/li&gt;
&lt;li&gt;PostgreSQL with pgvector for vector search&lt;/li&gt;
&lt;li&gt;Amazon Bedrock for LLM inference&lt;/li&gt;
&lt;li&gt;JUnit for evaluation test execution&lt;/li&gt;
&lt;li&gt;A curated evaluation dataset stored as JSON or database records&lt;/li&gt;
&lt;li&gt;An evaluation framework such as RAGAS or custom LLM-as-a-judge logic&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The evaluation pipeline can run during development and before production deployment.&lt;/p&gt;

&lt;p&gt;Example workflow:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Load the evaluation dataset.&lt;/li&gt;
&lt;li&gt;Execute each query against the RAG application.&lt;/li&gt;
&lt;li&gt;Capture retrieved documents and generated answers.&lt;/li&gt;
&lt;li&gt;Calculate retrieval metrics.&lt;/li&gt;
&lt;li&gt;Evaluate faithfulness and answer relevance.&lt;/li&gt;
&lt;li&gt;Validate source citations and grounding.&lt;/li&gt;
&lt;li&gt;Compare results against the previous model or prompt version.&lt;/li&gt;
&lt;li&gt;Fail the build if critical evaluation thresholds are not met.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;For example, a banking application might define an internal release gate requiring high faithfulness and retrieval recall for critical policy queries.&lt;/p&gt;

&lt;p&gt;The thresholds should be based on business risk, evaluation dataset quality, and observed production performance—not arbitrary universal values.&lt;/p&gt;




&lt;h2&gt;
  
  
  9. Production Considerations
&lt;/h2&gt;

&lt;p&gt;RAG evaluation should not stop after development.&lt;/p&gt;

&lt;p&gt;In production, monitor:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Retrieval latency&lt;/li&gt;
&lt;li&gt;LLM response latency&lt;/li&gt;
&lt;li&gt;Token consumption&lt;/li&gt;
&lt;li&gt;Retrieval failure rate&lt;/li&gt;
&lt;li&gt;Unsupported answer rate&lt;/li&gt;
&lt;li&gt;User feedback&lt;/li&gt;
&lt;li&gt;Source document freshness&lt;/li&gt;
&lt;li&gt;Model and prompt version changes&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For sensitive domains, also validate:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;User authorization before document retrieval&lt;/li&gt;
&lt;li&gt;PII protection&lt;/li&gt;
&lt;li&gt;Tenant-level data isolation&lt;/li&gt;
&lt;li&gt;Prompt injection resistance&lt;/li&gt;
&lt;li&gt;Audit logging&lt;/li&gt;
&lt;li&gt;Human escalation for high-risk decisions&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Evaluation should be performed whenever there is a significant change to the embedding model, chunking strategy, vector database configuration, prompt, LLM, or source documents.&lt;/p&gt;




&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;RAG evaluation is essential for building reliable enterprise AI applications.&lt;/p&gt;

&lt;p&gt;The four dimensions provide complementary insights:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Faithfulness&lt;/strong&gt; checks whether the answer is supported by retrieved context.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Answer Relevance&lt;/strong&gt; checks whether the response addresses the user's question.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Retrieval Quality&lt;/strong&gt; checks whether the right documents were found.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Grounding&lt;/strong&gt; checks whether the answer is traceable to trustworthy evidence.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A production RAG system should not be evaluated only by how fluent or impressive its answers sound.&lt;/p&gt;

&lt;p&gt;It should be evaluated by how accurately it retrieves information, how reliably it generates supported answers, and how safely it handles uncertainty.&lt;/p&gt;

&lt;p&gt;For enterprise AI, the goal is not simply to generate answers.&lt;/p&gt;

&lt;p&gt;The goal is to generate &lt;strong&gt;reliable, relevant, evidence-backed answers that can be trusted.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Author: Ram The Architect (RTA)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Follow me for more practical insights on Java 21 | Spring Boot | Microservices | Apache Kafka | AWS | System Design | GenAI&lt;/p&gt;

&lt;p&gt;Github: &lt;a href="https://github.com/Ramu-fsd/enterprise-banking-microservices" rel="noopener noreferrer"&gt;https://github.com/Ramu-fsd/enterprise-banking-microservices&lt;/a&gt;&lt;br&gt;
Linkedin: &lt;a href="https://www.linkedin.com/in/ramuboya/" rel="noopener noreferrer"&gt;https://www.linkedin.com/in/ramuboya/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;#Java #AI #RAG #MachineLearning&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>ai</category>
      <category>rag</category>
      <category>machinelearning</category>
      <category>java</category>
    </item>
    <item>
      <title>JPA Performance: N+1 Queries, Fetch Strategies and Batch Processing</title>
      <dc:creator>Ramanjaneyulu Boya</dc:creator>
      <pubDate>Sun, 29 Nov 2026 13:37:34 +0000</pubDate>
      <link>https://dev.to/ramthearchitect/jpa-performance-n1-queries-fetch-strategies-and-batch-processing-559</link>
      <guid>https://dev.to/ramthearchitect/jpa-performance-n1-queries-fetch-strategies-and-batch-processing-559</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Java Persistence API (JPA) simplifies database interactions by allowing developers to work with Java objects instead of writing SQL for every operation.&lt;/p&gt;

&lt;p&gt;With Spring Boot, Spring Data JPA, and Hibernate, we can build data-driven applications quickly using repositories, entity relationships, and transaction management.&lt;/p&gt;

&lt;p&gt;However, &lt;strong&gt;writing clean JPA code does not automatically guarantee efficient database access.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A simple repository method can unexpectedly execute hundreds of SQL queries. Loading a collection of entities can consume excessive memory. Updating thousands of records one by one can significantly increase database round trips.&lt;/p&gt;

&lt;p&gt;In enterprise applications such as banking, payments, insurance, and customer management systems, these issues can directly impact:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;API response time&lt;/li&gt;
&lt;li&gt;Database connection pool utilization&lt;/li&gt;
&lt;li&gt;Transaction throughput&lt;/li&gt;
&lt;li&gt;CPU and memory consumption&lt;/li&gt;
&lt;li&gt;Application scalability&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In this article, we will explore three important JPA performance topics:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;N+1 query problem&lt;/li&gt;
&lt;li&gt;Fetch strategies and optimized entity loading&lt;/li&gt;
&lt;li&gt;Batch processing for efficient database operations&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let's understand these concepts with practical Spring Boot and Hibernate examples.&lt;/p&gt;




&lt;h2&gt;
  
  
  1. Understanding the N+1 Query Problem
&lt;/h2&gt;

&lt;p&gt;The N+1 query problem occurs when an application executes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;One query to retrieve a collection of parent entities&lt;/li&gt;
&lt;li&gt;N additional queries to retrieve related entities individually&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Consider a banking application with customers and their accounts.&lt;/p&gt;

&lt;h3&gt;
  
  
  Entity relationships
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Entity&lt;/span&gt;
&lt;span class="nd"&gt;@Table&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"customers"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Customer&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="nd"&gt;@Id&lt;/span&gt;
    &lt;span class="nd"&gt;@GeneratedValue&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;strategy&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;GenerationType&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;IDENTITY&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nd"&gt;@OneToMany&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;mappedBy&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"customer"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Account&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;accounts&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The Account entity:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Entity&lt;/span&gt;
&lt;span class="nd"&gt;@Table&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"accounts"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Account&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="nd"&gt;@Id&lt;/span&gt;
    &lt;span class="nd"&gt;@GeneratedValue&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;strategy&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;GenerationType&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;IDENTITY&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt; &lt;span class="n"&gt;accountNumber&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;BigDecimal&lt;/span&gt; &lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nd"&gt;@ManyToOne&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;fetch&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;FetchType&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;LAZY&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nd"&gt;@JoinColumn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"customer_id"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;Customer&lt;/span&gt; &lt;span class="n"&gt;customer&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One customer can have multiple accounts.&lt;/p&gt;

&lt;h3&gt;
  
  
  The problematic code
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kt"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Customer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;customers&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
        &lt;span class="n"&gt;customerRepository&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;findAll&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Customer&lt;/span&gt; &lt;span class="n"&gt;customer&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;customers&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;customer&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getAccounts&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;size&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At first glance, this looks perfectly reasonable.&lt;/p&gt;

&lt;p&gt;But Hibernate may execute the following SQL:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;
&lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;customers&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then, for every customer:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;
&lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;accounts&lt;/span&gt;
&lt;span class="k"&gt;WHERE&lt;/span&gt; &lt;span class="n"&gt;customer_id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If there are 100 customers, the application may execute:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1 + 100 = 101 SQL queries&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If there are 1,000 customers, it may execute 1,001 queries.&lt;/p&gt;

&lt;p&gt;This is the N+1 query problem.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fvbkyrebrm1e6nd9s3qmh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fvbkyrebrm1e6nd9s3qmh.png" alt="JPA N+1 QUERY PROBLEM" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Why is N+1 a serious problem?
&lt;/h3&gt;

&lt;p&gt;Each database query introduces overhead:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Network communication&lt;/li&gt;
&lt;li&gt;SQL parsing and execution&lt;/li&gt;
&lt;li&gt;Database connection usage&lt;/li&gt;
&lt;li&gt;Result-set processing&lt;/li&gt;
&lt;li&gt;Hibernate entity hydration&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Even if each query takes only a few milliseconds, hundreds of sequential database calls can significantly increase response time.&lt;/p&gt;

&lt;p&gt;In a high-throughput payment or customer service, this can become a major performance bottleneck.&lt;/p&gt;




&lt;h2&gt;
  
  
  2. Fetch Strategies: LAZY vs EAGER
&lt;/h2&gt;

&lt;p&gt;JPA provides two primary fetch strategies.&lt;/p&gt;

&lt;h3&gt;
  
  
  LAZY fetching
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@OneToMany&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;fetch&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;FetchType&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;LAZY&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Account&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;accounts&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The related entities are loaded only when accessed.&lt;/p&gt;

&lt;p&gt;Advantages:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Avoids loading unnecessary data&lt;/li&gt;
&lt;li&gt;Reduces initial query size&lt;/li&gt;
&lt;li&gt;Helps control memory consumption&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;However, accessing lazy relationships inside a loop can cause N+1 queries.&lt;/p&gt;

&lt;h3&gt;
  
  
  EAGER fetching
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@ManyToOne&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;fetch&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;FetchType&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;EAGER&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;Customer&lt;/span&gt; &lt;span class="n"&gt;customer&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;EAGER means the association must be initialized as part of the entity loading process.&lt;/p&gt;

&lt;p&gt;Important: EAGER does not guarantee that Hibernate will always use a SQL JOIN.&lt;/p&gt;

&lt;p&gt;Hibernate may execute additional queries to satisfy eager loading, depending on the query and mapping.&lt;/p&gt;

&lt;p&gt;Therefore, changing LAZY to EAGER is not a reliable solution to the N+1 problem.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Best practice:&lt;/strong&gt; Prefer LAZY associations and explicitly define the fetch plan required by each use case.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fbk4w1525vrugfgyjs04u.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fbk4w1525vrugfgyjs04u.png" alt="JPA FETCH STRATEGIES" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  3. Solving N+1 Using JOIN FETCH
&lt;/h2&gt;

&lt;p&gt;One of the most common solutions is JPQL JOIN FETCH.&lt;/p&gt;

&lt;p&gt;Instead of loading customers first and accounts separately, we fetch both in a single query.&lt;/p&gt;

&lt;h3&gt;
  
  
  Repository implementation
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Repository&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;interface&lt;/span&gt; &lt;span class="nc"&gt;CustomerRepository&lt;/span&gt;
        &lt;span class="k"&gt;extends&lt;/span&gt; &lt;span class="nc"&gt;JpaRepository&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Customer&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;Long&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="nd"&gt;@Query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"""
        SELECT DISTINCT c
        FROM Customer c
        LEFT JOIN FETCH c.accounts
        """&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="kt"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Customer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;findAllWithAccounts&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now execute:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kt"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Customer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;customers&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
        &lt;span class="n"&gt;customerRepository&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;findAllWithAccounts&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Hibernate can generate SQL similar to:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt;
    &lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;account_number&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;customer_id&lt;/span&gt;
&lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;customers&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt;
&lt;span class="k"&gt;LEFT&lt;/span&gt; &lt;span class="k"&gt;JOIN&lt;/span&gt; &lt;span class="n"&gt;accounts&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt;
    &lt;span class="k"&gt;ON&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;customer_id&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Instead of 101 queries, the application can retrieve the customers and their accounts using one SQL query.&lt;/p&gt;

&lt;h3&gt;
  
  
  Why LEFT JOIN FETCH?
&lt;/h3&gt;

&lt;p&gt;A customer may not have any accounts.&lt;/p&gt;

&lt;p&gt;Using LEFT JOIN ensures that customers without accounts are still included.&lt;/p&gt;

&lt;h3&gt;
  
  
  Why DISTINCT?
&lt;/h3&gt;

&lt;p&gt;A JOIN produces one row per matching account.&lt;/p&gt;

&lt;p&gt;If a customer has three accounts, that customer may appear in three rows in the SQL result.&lt;/p&gt;

&lt;p&gt;DISTINCT helps ensure the root Customer entities are returned without duplicate references in the result list.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fgu87boye6q5pvnh7yyte.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fgu87boye6q5pvnh7yyte.png" alt="JOIN FETCH OPTIMIZATION" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Important pagination limitation
&lt;/h3&gt;

&lt;p&gt;Be careful when combining collection JOIN FETCH with pagination.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"""
    SELECT DISTINCT c
    FROM Customer c
    LEFT JOIN FETCH c.accounts
    """&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nc"&gt;Page&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Customer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;findAllWithAccounts&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Pageable&lt;/span&gt; &lt;span class="n"&gt;pageable&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This can cause inefficient pagination or in-memory pagination because the SQL result contains multiple rows per customer.&lt;/p&gt;

&lt;p&gt;For paginated APIs, consider:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Fetch a page of customer IDs.&lt;/li&gt;
&lt;li&gt;Fetch the required customers and accounts for those IDs.&lt;/li&gt;
&lt;li&gt;Restore the desired ordering if necessary.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"""
    SELECT c.id
    FROM Customer c
    ORDER BY c.id
    """&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nc"&gt;Page&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;Long&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;findCustomerIds&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Pageable&lt;/span&gt; &lt;span class="n"&gt;pageable&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then fetch the entities:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"""
    SELECT DISTINCT c
    FROM Customer c
    LEFT JOIN FETCH c.accounts
    WHERE c.id IN :ids
    """&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="kt"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Customer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;findCustomersWithAccounts&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="nd"&gt;@Param&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"ids"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="kt"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;Long&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;ids&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This approach avoids applying pagination directly to a collection fetch join.&lt;/p&gt;




&lt;h2&gt;
  
  
  4. Solving N+1 Using @EntityGraph
&lt;/h2&gt;

&lt;p&gt;Another powerful approach is the JPA EntityGraph.&lt;/p&gt;

&lt;p&gt;It allows us to specify which relationships should be fetched for a particular repository method without changing the entity's default fetch strategy.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Repository&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;interface&lt;/span&gt; &lt;span class="nc"&gt;CustomerRepository&lt;/span&gt;
        &lt;span class="k"&gt;extends&lt;/span&gt; &lt;span class="nc"&gt;JpaRepository&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Customer&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;Long&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="nd"&gt;@EntityGraph&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;attributePaths&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"accounts"&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="kt"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Customer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;findByNameContaining&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="kt"&gt;String&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The entity mapping remains LAZY:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@OneToMany&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;mappedBy&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"customer"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
           &lt;span class="n"&gt;fetch&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;FetchType&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;LAZY&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Account&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;accounts&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But for this repository method, we request accounts to be loaded as part of the fetch plan.&lt;/p&gt;

&lt;p&gt;EntityGraph is particularly useful when:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Different API endpoints need different relationships&lt;/li&gt;
&lt;li&gt;You want to keep entity mappings clean&lt;/li&gt;
&lt;li&gt;You want to avoid writing multiple JPQL queries&lt;/li&gt;
&lt;li&gt;You need reusable repository methods with specific fetch requirements&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Hibernate may choose a JOIN or another query strategy depending on the mapping and provider behavior, so always inspect the generated SQL.&lt;/p&gt;




&lt;h2&gt;
  
  
  5. Solving N+1 Using Hibernate Batch Fetching
&lt;/h2&gt;

&lt;p&gt;Sometimes JOIN FETCH is not the best option.&lt;/p&gt;

&lt;p&gt;For example, an application may need to load customers and their accounts, but joining all collections could produce a very large result set.&lt;/p&gt;

&lt;p&gt;Hibernate provides batch fetching to reduce the number of secondary queries.&lt;/p&gt;

&lt;h3&gt;
  
  
  Configure batch fetching
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@OneToMany&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;mappedBy&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"customer"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nd"&gt;@BatchSize&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;size&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;50&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Account&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;accounts&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or configure it globally:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight properties"&gt;&lt;code&gt;&lt;span class="na"&gt;spring.jpa.properties.hibernate.default_batch_fetch_size&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;50&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When Hibernate initializes lazy associations, it can fetch multiple collections in a single query using an IN clause.&lt;/p&gt;

&lt;p&gt;Instead of:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;
&lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;accounts&lt;/span&gt;
&lt;span class="k"&gt;WHERE&lt;/span&gt; &lt;span class="n"&gt;customer_id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;
&lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;accounts&lt;/span&gt;
&lt;span class="k"&gt;WHERE&lt;/span&gt; &lt;span class="n"&gt;customer_id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;
&lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;accounts&lt;/span&gt;
&lt;span class="k"&gt;WHERE&lt;/span&gt; &lt;span class="n"&gt;customer_id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Hibernate may execute:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;
&lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;accounts&lt;/span&gt;
&lt;span class="k"&gt;WHERE&lt;/span&gt; &lt;span class="n"&gt;customer_id&lt;/span&gt; &lt;span class="k"&gt;IN&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With a batch size of 50, Hibernate can often reduce 100 individual collection queries to approximately two batch queries.&lt;/p&gt;

&lt;p&gt;The exact number depends on the number of associations initialized, the persistence context, and Hibernate's batching behavior.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Feujmb4oartsnqesu4w5h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Feujmb4oartsnqesu4w5h.png" alt="HIBERNATE BATCH FETCHING" width="800" height="451"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  JOIN FETCH vs Batch Fetching
&lt;/h3&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Feature&lt;/th&gt;
&lt;th&gt;JOIN FETCH&lt;/th&gt;
&lt;th&gt;Batch Fetching&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Query strategy&lt;/td&gt;
&lt;td&gt;SQL JOIN&lt;/td&gt;
&lt;td&gt;Multiple IDs in IN clause&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Database round trips&lt;/td&gt;
&lt;td&gt;Often one&lt;/td&gt;
&lt;td&gt;Reduced&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Duplicate root rows&lt;/td&gt;
&lt;td&gt;Possible&lt;/td&gt;
&lt;td&gt;Avoided&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Large collections&lt;/td&gt;
&lt;td&gt;May produce huge result sets&lt;/td&gt;
&lt;td&gt;Often more manageable&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Pagination&lt;/td&gt;
&lt;td&gt;Collection pagination is problematic&lt;/td&gt;
&lt;td&gt;Generally more suitable&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Best use&lt;/td&gt;
&lt;td&gt;Small, known fetch graphs&lt;/td&gt;
&lt;td&gt;Multiple lazy associations&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;There is no universal best strategy. Choose based on the query, relationship cardinality, and expected result size.&lt;/p&gt;




&lt;h2&gt;
  
  
  6. Batch Processing: INSERT, UPDATE and DELETE
&lt;/h2&gt;

&lt;p&gt;Fetch optimization is only one part of JPA performance.&lt;/p&gt;

&lt;p&gt;When an application inserts or updates thousands of records, executing one SQL statement per entity can become expensive.&lt;/p&gt;

&lt;p&gt;Hibernate supports JDBC batching to group multiple statements into fewer database round trips.&lt;/p&gt;

&lt;h3&gt;
  
  
  Enable JDBC batching
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight properties"&gt;&lt;code&gt;&lt;span class="na"&gt;spring.jpa.properties.hibernate.jdbc.batch_size&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;50&lt;/span&gt;

&lt;span class="na"&gt;spring.jpa.properties.hibernate.order_inserts&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;

&lt;span class="na"&gt;spring.jpa.properties.hibernate.order_updates&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;These properties help Hibernate group compatible INSERT and UPDATE statements.&lt;/p&gt;

&lt;h3&gt;
  
  
  Example: Batch insert
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Transactional&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;saveAccounts&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="kt"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Account&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;accounts&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Account&lt;/span&gt; &lt;span class="n"&gt;account&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;accounts&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;accountRepository&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;save&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;account&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Although this code calls save() repeatedly, Hibernate may defer SQL execution until flush time.&lt;/p&gt;

&lt;p&gt;With JDBC batching enabled, compatible INSERT statements can be sent in batches.&lt;/p&gt;

&lt;p&gt;However, batching behavior depends on the identifier strategy.&lt;/p&gt;

&lt;p&gt;For example, IDENTITY-based generation often prevents Hibernate from batching INSERT statements because the generated identifier must be obtained immediately.&lt;/p&gt;

&lt;p&gt;Sequence-based identifiers are generally more batch-friendly when supported by the database and Hibernate configuration.&lt;/p&gt;

&lt;h3&gt;
  
  
  Important distinction
&lt;/h3&gt;

&lt;p&gt;JDBC batching reduces database round trips.&lt;/p&gt;

&lt;p&gt;It does not automatically reduce the number of SQL statements or eliminate the memory consumed by managed entities.&lt;/p&gt;

&lt;p&gt;For large imports, we need a different approach.&lt;/p&gt;




&lt;h2&gt;
  
  
  7. Processing Large Datasets Using flush() and clear()
&lt;/h2&gt;

&lt;p&gt;Consider importing 100,000 customer accounts.&lt;/p&gt;

&lt;p&gt;If every entity remains managed by the persistence context, Hibernate must track a large number of objects.&lt;/p&gt;

&lt;p&gt;This can increase memory usage and dirty-checking overhead.&lt;/p&gt;

&lt;p&gt;A common solution is to periodically flush and clear the persistence context.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Transactional&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;importAccounts&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="kt"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Account&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;accounts&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;batchSize&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;50&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;accounts&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;size&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

        &lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;persist&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;accounts&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;%&lt;/span&gt; &lt;span class="n"&gt;batchSize&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

            &lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;flush&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

            &lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;clear&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;flush&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;clear&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  What does flush() do?
&lt;/h3&gt;

&lt;p&gt;flush() synchronizes pending persistence-context changes with the database.&lt;/p&gt;

&lt;p&gt;It does not commit the transaction.&lt;/p&gt;

&lt;h3&gt;
  
  
  What does clear() do?
&lt;/h3&gt;

&lt;p&gt;clear() detaches all managed entities from the persistence context.&lt;/p&gt;

&lt;p&gt;This helps prevent the first-level cache from growing continuously during large batch operations.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fkf46hf7j7kcdo49ywdou.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fkf46hf7j7kcdo49ywdou.png" alt="JPA BATCH INSERT PROCESS" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Important considerations
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;flush() does not commit the transaction.&lt;/li&gt;
&lt;li&gt;clear() detaches all managed entities.&lt;/li&gt;
&lt;li&gt;Accessing detached entities may cause lazy-loading problems.&lt;/li&gt;
&lt;li&gt;Use a transaction strategy appropriate for the business operation.&lt;/li&gt;
&lt;li&gt;For very large imports, consider processing multiple transactions rather than one enormous transaction.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  8. Bulk UPDATE and DELETE Using JPQL
&lt;/h2&gt;

&lt;p&gt;For certain operations, loading every entity into memory is unnecessary.&lt;/p&gt;

&lt;p&gt;Suppose we need to deactivate 10,000 inactive accounts.&lt;/p&gt;

&lt;p&gt;A normal approach might load each account, modify it, and save it individually.&lt;/p&gt;

&lt;p&gt;Instead, use a bulk update:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Modifying&lt;/span&gt;
&lt;span class="nd"&gt;@Query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"""
    UPDATE Account a
    SET a.status = 'INACTIVE'
    WHERE a.lastActivityDate &amp;lt; :cutoffDate
    """&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;deactivateInactiveAccounts&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="nd"&gt;@Param&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"cutoffDate"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="nc"&gt;LocalDate&lt;/span&gt; &lt;span class="n"&gt;cutoffDate&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Service:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Transactional&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;deactivateAccounts&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="nc"&gt;LocalDate&lt;/span&gt; &lt;span class="n"&gt;cutoffDate&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;accountRepository&lt;/span&gt;
            &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;deactivateInactiveAccounts&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cutoffDate&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Hibernate can execute this as a single SQL UPDATE statement.&lt;/p&gt;

&lt;h3&gt;
  
  
  Bulk operation warning
&lt;/h3&gt;

&lt;p&gt;JPQL bulk UPDATE and DELETE operations bypass normal entity-by-entity processing.&lt;/p&gt;

&lt;p&gt;They do not automatically synchronize already-managed entities in the persistence context.&lt;/p&gt;

&lt;p&gt;If the same entities are already loaded, their in-memory state may become stale.&lt;/p&gt;

&lt;p&gt;You may need:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;flush&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;updated&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;accountRepository&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;deactivateInactiveAccounts&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cutoffDate&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;clear&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Also remember that bulk operations may bypass entity lifecycle callbacks and automatic optimistic-lock handling.&lt;/p&gt;

&lt;p&gt;Use them carefully when business rules depend on entity listeners, auditing, or version fields.&lt;/p&gt;




&lt;h2&gt;
  
  
  9. How to Identify JPA Performance Problems
&lt;/h2&gt;

&lt;p&gt;Never optimize JPA based only on assumptions.&lt;/p&gt;

&lt;p&gt;Measure the actual SQL generated by Hibernate.&lt;/p&gt;

&lt;h3&gt;
  
  
  Enable SQL logging
&lt;/h3&gt;

&lt;p&gt;For local development:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight properties"&gt;&lt;code&gt;&lt;span class="na"&gt;spring.jpa.show-sql&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;

&lt;span class="na"&gt;spring.jpa.properties.hibernate.format_sql&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For more detailed logging:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight properties"&gt;&lt;code&gt;&lt;span class="na"&gt;logging.level.org.hibernate.SQL&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="no"&gt;DEBUG&lt;/span&gt;

&lt;span class="na"&gt;logging.level.org.hibernate.orm.jdbc.bind&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="no"&gt;TRACE&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Avoid enabling bind-parameter TRACE logging in production because it can expose sensitive customer or financial data.&lt;/p&gt;

&lt;h3&gt;
  
  
  Use Hibernate statistics
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight properties"&gt;&lt;code&gt;&lt;span class="na"&gt;spring.jpa.properties.hibernate.generate_statistics&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Hibernate statistics can help identify:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Entity fetch counts&lt;/li&gt;
&lt;li&gt;Collection fetch counts&lt;/li&gt;
&lt;li&gt;Query execution counts&lt;/li&gt;
&lt;li&gt;Second-level cache activity&lt;/li&gt;
&lt;li&gt;JDBC batching behavior&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In production, use controlled monitoring and SQL observability tools rather than enabling verbose logging indiscriminately.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fjbun4m829jvk4gkz4l9d.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fjbun4m829jvk4gkz4l9d.png" alt="JPA PERFORMANCE MONITORING" width="800" height="451"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  10. Real-World Fintech Example
&lt;/h2&gt;

&lt;p&gt;Consider a customer dashboard in a banking application.&lt;/p&gt;

&lt;p&gt;The dashboard displays:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Customer profile&lt;/li&gt;
&lt;li&gt;Active accounts&lt;/li&gt;
&lt;li&gt;Account balances&lt;/li&gt;
&lt;li&gt;Recent transactions&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A poorly optimized implementation may load customers, then accounts, then transactions individually.&lt;/p&gt;

&lt;p&gt;For 100 customers, this could result in hundreds of database queries.&lt;/p&gt;

&lt;p&gt;A better architecture uses different fetch plans for different requirements:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Use case&lt;/th&gt;
&lt;th&gt;Recommended approach&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Customer profile&lt;/td&gt;
&lt;td&gt;Direct entity or DTO projection&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Customer with accounts&lt;/td&gt;
&lt;td&gt;JOIN FETCH or EntityGraph&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Customer with many transactions&lt;/td&gt;
&lt;td&gt;Batch fetching or separate paginated query&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Account summary&lt;/td&gt;
&lt;td&gt;DTO projection&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Large account import&lt;/td&gt;
&lt;td&gt;JDBC batching with flush/clear&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Bulk account status update&lt;/td&gt;
&lt;td&gt;JPQL bulk UPDATE&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;For read-heavy APIs, DTO projections can be particularly effective because they retrieve only the required columns instead of loading complete entity graphs.&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;record&lt;/span&gt; &lt;span class="nc"&gt;AccountSummary&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="kt"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;accountId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="kt"&gt;String&lt;/span&gt; &lt;span class="n"&gt;accountNumber&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="nc"&gt;BigDecimal&lt;/span&gt; &lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Repository:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"""
    SELECT new com.example.dto.AccountSummary(
        a.id,
        a.accountNumber,
        a.balance
    )
    FROM Account a
    WHERE a.customer.id = :customerId
    """&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="kt"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;AccountSummary&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;findAccountSummaries&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="nd"&gt;@Param&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"customerId"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="kt"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;customerId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This avoids unnecessary entity hydration and reduces the amount of data transferred from the database.&lt;/p&gt;




&lt;h2&gt;
  
  
  11. JPA Performance Best Practices
&lt;/h2&gt;

&lt;p&gt;For production-grade Spring Boot applications, keep these principles in mind:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Prefer LAZY associations for entity relationships.&lt;/li&gt;
&lt;li&gt;Define explicit fetch plans for each use case.&lt;/li&gt;
&lt;li&gt;Use JOIN FETCH for small, predictable relationship graphs.&lt;/li&gt;
&lt;li&gt;Use EntityGraph when repository methods need different fetch plans.&lt;/li&gt;
&lt;li&gt;Consider batch fetching for multiple lazy associations.&lt;/li&gt;
&lt;li&gt;Avoid collection JOIN FETCH with direct pagination.&lt;/li&gt;
&lt;li&gt;Enable JDBC batching for compatible INSERT and UPDATE operations.&lt;/li&gt;
&lt;li&gt;Use flush() and clear() for large imports.&lt;/li&gt;
&lt;li&gt;Use bulk JPQL operations when entity lifecycle processing is not required.&lt;/li&gt;
&lt;li&gt;Prefer DTO projections for read-heavy APIs.&lt;/li&gt;
&lt;li&gt;Measure generated SQL and query counts.&lt;/li&gt;
&lt;li&gt;Never expose large entity graphs directly through REST APIs without controlling serialization and fetching.&lt;/li&gt;
&lt;/ol&gt;




&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;JPA and Hibernate provide powerful abstractions for database access, but performance depends on how we use them.&lt;/p&gt;

&lt;p&gt;The N+1 query problem is one of the most common performance issues in ORM-based applications. Fetch strategies, JOIN FETCH, EntityGraph, and batch fetching help control how related entities are loaded.&lt;/p&gt;

&lt;p&gt;JDBC batching, persistence-context management, and bulk operations help improve write performance and reduce memory overhead.&lt;/p&gt;

&lt;p&gt;As Java backend developers, we should focus not only on writing clean repository methods but also on understanding the SQL generated underneath.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The real goal is not to eliminate every SQL query. It is to minimize unnecessary database round trips while maintaining correctness, scalability, and maintainability.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In enterprise applications, good JPA performance is an important part of building reliable and scalable backend systems.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Author: Ram The Architect (RTA)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Follow me for more practical insights on Java 21 | Spring Boot | Microservices | Apache Kafka | AWS | System Design | GenAI&lt;/p&gt;

&lt;p&gt;Github: &lt;a href="https://github.com/Ramu-fsd/enterprise-banking-microservices" rel="noopener noreferrer"&gt;https://github.com/Ramu-fsd/enterprise-banking-microservices&lt;/a&gt;&lt;br&gt;
Linkedin: &lt;a href="https://www.linkedin.com/in/ramuboya/" rel="noopener noreferrer"&gt;https://www.linkedin.com/in/ramuboya/&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  Java #SpringBoot #JPA #Hibernate #PerformanceOptimization #BackendDevelopment #Microservices #DatabasePerformance #Java21 #DevTo
&lt;/h1&gt;

</description>
      <category>java</category>
      <category>springboot</category>
      <category>hibernate</category>
      <category>performance</category>
    </item>
    <item>
      <title>What Happens Internally When a Spring Boot Application Starts?</title>
      <dc:creator>Ramanjaneyulu Boya</dc:creator>
      <pubDate>Sun, 29 Nov 2026 11:40:39 +0000</pubDate>
      <link>https://dev.to/ramthearchitect/what-happens-internally-when-a-spring-boot-application-starts-1i05</link>
      <guid>https://dev.to/ramthearchitect/what-happens-internally-when-a-spring-boot-application-starts-1i05</guid>
      <description>&lt;p&gt;Spring Boot makes application development remarkably simple.&lt;/p&gt;

&lt;p&gt;With just a few annotations and a &lt;code&gt;main()&lt;/code&gt; method, we can start a complete Java application with dependency injection, embedded Tomcat, database connectivity, REST APIs, security, and much more.&lt;/p&gt;

&lt;p&gt;But have you ever wondered what actually happens behind the scenes when we execute this?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@SpringBootApplication&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;BankingApplication&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;SpringApplication&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;run&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;BankingApplication&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What happens internally?&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;How does Spring Boot identify the application configuration?&lt;/li&gt;
&lt;li&gt;When are beans created?&lt;/li&gt;
&lt;li&gt;How does component scanning work?&lt;/li&gt;
&lt;li&gt;When does auto-configuration happen?&lt;/li&gt;
&lt;li&gt;How is embedded Tomcat started?&lt;/li&gt;
&lt;li&gt;When does the application become ready to receive requests?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Understanding these internals is important for debugging startup failures, improving application startup time, and designing reliable enterprise applications.&lt;/p&gt;

&lt;p&gt;Let's walk through the complete startup lifecycle of a Spring Boot application.&lt;/p&gt;




&lt;h2&gt;
  
  
  1. The Spring Boot Startup Entry Point
&lt;/h2&gt;

&lt;p&gt;Every Spring Boot application starts with the &lt;code&gt;main()&lt;/code&gt; method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nc"&gt;SpringApplication&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;run&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;BankingApplication&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;SpringApplication.run()&lt;/code&gt; method is the central entry point responsible for bootstrapping the application.&lt;/p&gt;

&lt;p&gt;Internally, Spring Boot performs several important operations:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Creates a &lt;code&gt;SpringApplication&lt;/code&gt; instance.&lt;/li&gt;
&lt;li&gt;Determines the application type.&lt;/li&gt;
&lt;li&gt;Loads initializers and listeners.&lt;/li&gt;
&lt;li&gt;Prepares the application environment.&lt;/li&gt;
&lt;li&gt;Creates the application context.&lt;/li&gt;
&lt;li&gt;Registers bean definitions.&lt;/li&gt;
&lt;li&gt;Refreshes the application context.&lt;/li&gt;
&lt;li&gt;Starts the embedded web server.&lt;/li&gt;
&lt;li&gt;Executes application startup callbacks.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Important:&lt;/strong&gt; &lt;code&gt;SpringApplication.run()&lt;/code&gt; does not simply create objects and start Tomcat. It orchestrates the entire Spring container initialization process.&lt;/p&gt;




&lt;h2&gt;
  
  
  &lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fe3ocw80atlg3fk919v5e.png" alt="Spring Boot Startup Lifecycle" width="800" height="410"&gt;
&lt;/h2&gt;

&lt;h2&gt;
  
  
  2. SpringApplication Object Initialization
&lt;/h2&gt;

&lt;p&gt;Before the application context is created, Spring Boot initializes the &lt;code&gt;SpringApplication&lt;/code&gt; object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;SpringApplication&lt;/span&gt; &lt;span class="n"&gt;app&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
        &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;SpringApplication&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;BankingApplication&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="n"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;run&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;During initialization, Spring Boot determines the application type.&lt;/p&gt;

&lt;p&gt;Common application types include:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Application Type&lt;/th&gt;
&lt;th&gt;Description&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;SERVLET&lt;/td&gt;
&lt;td&gt;Traditional web applications using Spring MVC&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;REACTIVE&lt;/td&gt;
&lt;td&gt;Reactive applications using WebFlux&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;NONE&lt;/td&gt;
&lt;td&gt;Non-web applications&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;For a typical Spring MVC application, Spring Boot identifies the application as a servlet-based application.&lt;/p&gt;

&lt;p&gt;It also discovers and prepares:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Application context initializers&lt;/li&gt;
&lt;li&gt;Application listeners&lt;/li&gt;
&lt;li&gt;Primary application sources&lt;/li&gt;
&lt;li&gt;Startup configuration&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;These components participate in different stages of the startup lifecycle.&lt;/p&gt;




&lt;h2&gt;
  
  
  3. Environment Preparation
&lt;/h2&gt;

&lt;p&gt;Spring Boot prepares the application environment before creating the application context.&lt;/p&gt;

&lt;p&gt;The environment contains configuration properties used throughout the application.&lt;/p&gt;

&lt;p&gt;For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight properties"&gt;&lt;code&gt;&lt;span class="na"&gt;server.port&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;8081&lt;/span&gt;

&lt;span class="na"&gt;spring.application.name&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;banking&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;service&lt;/span&gt;

&lt;span class="na"&gt;spring.datasource.url&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;jdbc&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="n"&gt;postgresql&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="c1"&gt;//localhost:5432/banking&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Spring Boot loads configuration from multiple sources, including:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;application.properties&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;application.yml&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Environment variables&lt;/li&gt;
&lt;li&gt;Command-line arguments&lt;/li&gt;
&lt;li&gt;JVM system properties&lt;/li&gt;
&lt;li&gt;External configuration sources&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The configuration values are exposed through Spring's &lt;code&gt;Environment&lt;/code&gt; abstraction.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Component&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ApplicationConfiguration&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;Environment&lt;/span&gt; &lt;span class="n"&gt;environment&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;ApplicationConfiguration&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Environment&lt;/span&gt; &lt;span class="n"&gt;environment&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;environment&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;environment&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;printPort&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="n"&gt;environment&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getProperty&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"server.port"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Spring Boot also determines which profiles are active.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight properties"&gt;&lt;code&gt;&lt;span class="na"&gt;spring.profiles.active&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;dev&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Profile-specific configuration can then be loaded:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;application-dev.properties
application-qa.properties
application-prod.properties
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This allows the same application code to run with different configurations across environments.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Production insight:&lt;/strong&gt; Configuration should be externalized. Database passwords, API keys, and other secrets should not be hardcoded into application properties or source code.&lt;/p&gt;




&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F3bmexlq4omsvw1tsh743.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F3bmexlq4omsvw1tsh743.png" alt="Spring Boot Environment and Configuration Loading" width="800" height="409"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  4. ApplicationContext Creation
&lt;/h2&gt;

&lt;p&gt;After preparing the environment, Spring Boot creates the application context.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;ApplicationContext&lt;/code&gt; is the central container of the Spring application.&lt;/p&gt;

&lt;p&gt;It manages:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Bean definitions&lt;/li&gt;
&lt;li&gt;Bean instances&lt;/li&gt;
&lt;li&gt;Dependency injection&lt;/li&gt;
&lt;li&gt;Bean lifecycle&lt;/li&gt;
&lt;li&gt;Application events&lt;/li&gt;
&lt;li&gt;Resource loading&lt;/li&gt;
&lt;li&gt;Environment access&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For a Spring MVC application, Spring Boot typically creates an instance of:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;AnnotationConfigServletWebServerApplicationContext&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This context supports annotation-based configuration and embedded servlet web servers.&lt;/p&gt;

&lt;p&gt;For a non-web application, a different application context implementation may be selected.&lt;/p&gt;

&lt;p&gt;At this stage, the application context exists, but the application is not yet fully initialized.&lt;/p&gt;




&lt;h2&gt;
  
  
  5. What Does @SpringBootApplication Actually Do?
&lt;/h2&gt;

&lt;p&gt;One of the most important annotations in Spring Boot is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@SpringBootApplication&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It combines three major annotations.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@SpringBootConfiguration&lt;/span&gt;

&lt;span class="nd"&gt;@EnableAutoConfiguration&lt;/span&gt;

&lt;span class="nd"&gt;@ComponentScan&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's understand each one.&lt;/p&gt;

&lt;h3&gt;
  
  
  @SpringBootConfiguration
&lt;/h3&gt;

&lt;p&gt;This identifies the class as a Spring Boot configuration class.&lt;/p&gt;

&lt;p&gt;It is a specialized form of &lt;code&gt;@Configuration&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  @EnableAutoConfiguration
&lt;/h3&gt;

&lt;p&gt;This enables Spring Boot's auto-configuration mechanism.&lt;/p&gt;

&lt;p&gt;Spring Boot examines the application environment, classpath, and existing bean definitions to determine which configurations may be appropriate.&lt;/p&gt;

&lt;h3&gt;
  
  
  @ComponentScan
&lt;/h3&gt;

&lt;p&gt;This enables component scanning.&lt;/p&gt;

&lt;p&gt;Spring scans the package containing the main application class and its subpackages for components such as:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Component&lt;/span&gt;
&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="nd"&gt;@Repository&lt;/span&gt;
&lt;span class="nd"&gt;@Controller&lt;/span&gt;
&lt;span class="nd"&gt;@RestController&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;These components are registered as bean definitions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Best practice:&lt;/strong&gt; Place the main application class in a root package so that component scanning can discover the application's components consistently.&lt;/p&gt;




&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fsrl8f6u755ty9jc1yw8x.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fsrl8f6u755ty9jc1yw8x.png" alt="@SpringBootApplication Internals" width="799" height="409"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  6. Bean Definition Registration
&lt;/h2&gt;

&lt;p&gt;Spring does not immediately create every bean when it discovers a component.&lt;/p&gt;

&lt;p&gt;First, it registers bean definitions.&lt;/p&gt;

&lt;p&gt;A bean definition contains metadata about a bean, such as:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Bean class&lt;/li&gt;
&lt;li&gt;Scope&lt;/li&gt;
&lt;li&gt;Dependencies&lt;/li&gt;
&lt;li&gt;Constructor information&lt;/li&gt;
&lt;li&gt;Initialization methods&lt;/li&gt;
&lt;li&gt;Lifecycle configuration&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;PaymentService&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;PaymentRepository&lt;/span&gt; &lt;span class="n"&gt;repository&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;PaymentService&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;PaymentRepository&lt;/span&gt; &lt;span class="n"&gt;repository&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;repository&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;repository&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Spring discovers &lt;code&gt;PaymentService&lt;/code&gt; and registers its bean definition.&lt;/p&gt;

&lt;p&gt;It also discovers the dependency on &lt;code&gt;PaymentRepository&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;At this point, Spring has information about the bean, but the actual object may not yet exist.&lt;/p&gt;

&lt;p&gt;This distinction is important:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bean definition registration is not the same as bean instantiation.&lt;/strong&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  7. Auto-Configuration: How Spring Boot Reduces Boilerplate
&lt;/h2&gt;

&lt;p&gt;One of the biggest advantages of Spring Boot is auto-configuration.&lt;/p&gt;

&lt;p&gt;Suppose we add the following dependency:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight xml"&gt;&lt;code&gt;&lt;span class="nt"&gt;&amp;lt;dependency&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;groupId&amp;gt;&lt;/span&gt;org.springframework.boot&lt;span class="nt"&gt;&amp;lt;/groupId&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;artifactId&amp;gt;&lt;/span&gt;spring-boot-starter-web&lt;span class="nt"&gt;&amp;lt;/artifactId&amp;gt;&lt;/span&gt;
&lt;span class="nt"&gt;&amp;lt;/dependency&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Spring Boot can automatically configure several web application components when the relevant conditions are satisfied.&lt;/p&gt;

&lt;p&gt;Examples include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Spring MVC infrastructure&lt;/li&gt;
&lt;li&gt;JSON message converters&lt;/li&gt;
&lt;li&gt;Embedded servlet web server&lt;/li&gt;
&lt;li&gt;DispatcherServlet&lt;/li&gt;
&lt;li&gt;Web-related infrastructure beans&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Auto-configuration is driven by conditional configuration classes.&lt;/p&gt;

&lt;p&gt;For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Configuration&lt;/span&gt;
&lt;span class="nd"&gt;@ConditionalOnClass&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;DataSource&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nd"&gt;@ConditionalOnMissingBean&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;DataSource&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;CustomDatabaseConfiguration&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="c1"&gt;// Database configuration&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The conditions determine whether a configuration should be applied.&lt;/p&gt;

&lt;p&gt;Spring Boot's auto-configuration mechanism uses conditions such as:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@ConditionalOnClass&lt;/span&gt;
&lt;span class="nd"&gt;@ConditionalOnMissingBean&lt;/span&gt;
&lt;span class="nd"&gt;@ConditionalOnProperty&lt;/span&gt;
&lt;span class="nd"&gt;@ConditionalOnBean&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In modern Spring Boot versions, auto-configuration candidates are discovered through the framework's auto-configuration metadata and imports mechanism.&lt;/p&gt;

&lt;p&gt;The actual configurations are evaluated during configuration processing.&lt;/p&gt;

&lt;h3&gt;
  
  
  Example: Database Auto-Configuration
&lt;/h3&gt;

&lt;p&gt;If the application has the required database libraries and configuration, Spring Boot may configure a &lt;code&gt;DataSource&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight properties"&gt;&lt;code&gt;&lt;span class="na"&gt;spring.datasource.url&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;jdbc&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="n"&gt;postgresql&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="c1"&gt;//localhost:5432/banking&lt;/span&gt;
&lt;span class="na"&gt;spring.datasource.username&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;bank_user&lt;/span&gt;
&lt;span class="na"&gt;spring.datasource.password&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;$&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="no"&gt;DB_PASSWORD&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Spring Boot can configure the connection pool and related database infrastructure.&lt;/p&gt;

&lt;p&gt;If an application provides its own &lt;code&gt;DataSource&lt;/code&gt; bean, certain auto-configurations may back off because of conditions such as &lt;code&gt;@ConditionalOnMissingBean&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This is how Spring Boot provides sensible defaults while still allowing customization.&lt;/p&gt;




&lt;h2&gt;
  
  
  8. ApplicationContext Refresh — The Most Important Phase
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;refresh()&lt;/code&gt; method is one of the most important operations in the Spring application lifecycle.&lt;/p&gt;

&lt;p&gt;It initializes the Spring container and prepares it for use.&lt;/p&gt;

&lt;p&gt;During refresh, Spring performs several important operations.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 1: Prepare the BeanFactory
&lt;/h3&gt;

&lt;p&gt;Spring creates and prepares the internal &lt;code&gt;BeanFactory&lt;/code&gt;, which is responsible for managing bean definitions and bean creation.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 2: Execute BeanFactoryPostProcessors
&lt;/h3&gt;

&lt;p&gt;These processors can modify bean definitions before regular beans are instantiated.&lt;/p&gt;

&lt;p&gt;An important example is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;ConfigurationClassPostProcessor&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It processes configuration classes and handles annotations such as:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Configuration&lt;/span&gt;
&lt;span class="nd"&gt;@ComponentScan&lt;/span&gt;
&lt;span class="nd"&gt;@Bean&lt;/span&gt;
&lt;span class="nd"&gt;@Import&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is where much of the configuration class processing and component scanning takes place.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 3: Register BeanPostProcessors
&lt;/h3&gt;

&lt;p&gt;Spring registers processors that can customize beans before and after initialization.&lt;/p&gt;

&lt;p&gt;Examples include processors involved in:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Dependency injection&lt;/li&gt;
&lt;li&gt;AOP proxy creation&lt;/li&gt;
&lt;li&gt;Annotation processing&lt;/li&gt;
&lt;li&gt;Lifecycle callbacks&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Step 4: Instantiate Singleton Beans
&lt;/h3&gt;

&lt;p&gt;Spring creates non-lazy singleton beans.&lt;/p&gt;

&lt;p&gt;It resolves dependencies and injects them into constructors, fields, or setter methods.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 5: Initialize Beans
&lt;/h3&gt;

&lt;p&gt;Spring invokes applicable initialization callbacks.&lt;/p&gt;

&lt;p&gt;For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@PostConstruct&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;initialize&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"PaymentService initialized"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Other initialization mechanisms include:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;InitializingBean&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and custom initialization methods.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 6: Complete Context Refresh
&lt;/h3&gt;

&lt;p&gt;Spring completes the refresh process and publishes the relevant lifecycle events.&lt;/p&gt;

&lt;p&gt;For a web application, the embedded web server is also initialized during this overall refresh process.&lt;/p&gt;




&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F9d1cra2bt68wmzb3vtz6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F9d1cra2bt68wmzb3vtz6.png" alt="Inside ApplicationContext.refresh()" width="800" height="409"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  9. Dependency Injection and Bean Creation
&lt;/h2&gt;

&lt;p&gt;Let's consider a simple banking application.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@RestController&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;PaymentController&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;PaymentService&lt;/span&gt; &lt;span class="n"&gt;paymentService&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;PaymentController&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;PaymentService&lt;/span&gt; &lt;span class="n"&gt;paymentService&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;paymentService&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;paymentService&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;PaymentService&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;PaymentRepository&lt;/span&gt; &lt;span class="n"&gt;repository&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;PaymentService&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;PaymentRepository&lt;/span&gt; &lt;span class="n"&gt;repository&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;repository&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;repository&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Repository&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;PaymentRepository&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Spring resolves the dependency chain:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;PaymentController
       |
       v
PaymentService
       |
       v
PaymentRepository
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When creating the controller, Spring first resolves its required &lt;code&gt;PaymentService&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;While creating the service, Spring resolves its &lt;code&gt;PaymentRepository&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Once the dependencies are available, Spring constructs the objects and injects them.&lt;/p&gt;

&lt;p&gt;The resulting beans are managed by the Spring container.&lt;/p&gt;

&lt;p&gt;For singleton-scoped beans, Spring normally creates one shared instance per bean definition within the application context.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Important:&lt;/strong&gt; Singleton scope does not mean one object across the entire JVM. It means one managed instance per bean definition per Spring container.&lt;/p&gt;




&lt;h2&gt;
  
  
  10. Embedded Tomcat Startup
&lt;/h2&gt;

&lt;p&gt;For a typical Spring Boot web application, embedded Tomcat is started as part of application context refresh.&lt;/p&gt;

&lt;p&gt;Spring Boot creates a servlet web server through a &lt;code&gt;ServletWebServerFactory&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;TomcatServletWebServerFactory&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The web server infrastructure configures:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Server port&lt;/li&gt;
&lt;li&gt;Connectors&lt;/li&gt;
&lt;li&gt;Servlet context&lt;/li&gt;
&lt;li&gt;Filters&lt;/li&gt;
&lt;li&gt;Servlet registrations&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Spring MVC also configures the &lt;code&gt;DispatcherServlet&lt;/code&gt;, which acts as the front controller for incoming HTTP requests.&lt;/p&gt;

&lt;p&gt;A typical request flow is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Client
  |
  v
Embedded Tomcat
  |
  v
DispatcherServlet
  |
  v
Controller
  |
  v
Service
  |
  v
Repository
  |
  v
Database
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once the web server has successfully started, the application can begin accepting HTTP requests.&lt;/p&gt;




&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fzj4onr2x1epy8s0to9go.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fzj4onr2x1epy8s0to9go.png" alt="Spring Boot Embedded Tomcat Architecture" width="799" height="408"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  11. ApplicationRunner and CommandLineRunner
&lt;/h2&gt;

&lt;p&gt;After the application context has been refreshed and the application startup process has reached the runner phase, Spring Boot executes registered startup runners.&lt;/p&gt;

&lt;p&gt;Two common interfaces are:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;CommandLineRunner&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;ApplicationRunner&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Component&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;BankingStartupRunner&lt;/span&gt;
        &lt;span class="k"&gt;implements&lt;/span&gt; &lt;span class="nc"&gt;ApplicationRunner&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="nd"&gt;@Override&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;run&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ApplicationArguments&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="s2"&gt;"Banking application startup completed"&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;These interfaces are useful for executing startup tasks such as:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Loading reference data&lt;/li&gt;
&lt;li&gt;Validating startup configuration&lt;/li&gt;
&lt;li&gt;Initializing application-specific resources&lt;/li&gt;
&lt;li&gt;Performing controlled startup checks&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Use them carefully.&lt;/p&gt;

&lt;p&gt;Long-running operations inside startup runners can delay application readiness.&lt;/p&gt;

&lt;p&gt;For example, loading millions of records during startup can significantly increase deployment time.&lt;/p&gt;




&lt;h2&gt;
  
  
  12. When Is the Application Actually Ready?
&lt;/h2&gt;

&lt;p&gt;Spring Boot publishes several application lifecycle events.&lt;/p&gt;

&lt;p&gt;Some important events include:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Event&lt;/th&gt;
&lt;th&gt;Meaning&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;ApplicationStartingEvent&lt;/td&gt;
&lt;td&gt;Startup process begins&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;ApplicationEnvironmentPreparedEvent&lt;/td&gt;
&lt;td&gt;Environment is prepared&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;ApplicationContextInitializedEvent&lt;/td&gt;
&lt;td&gt;Context initialization phase&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;ApplicationPreparedEvent&lt;/td&gt;
&lt;td&gt;Context prepared before refresh&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;ContextRefreshedEvent&lt;/td&gt;
&lt;td&gt;Application context refreshed&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;ApplicationStartedEvent&lt;/td&gt;
&lt;td&gt;Application startup phase completed&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;ApplicationReadyEvent&lt;/td&gt;
&lt;td&gt;Application is ready for application-level traffic&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;The exact sequence and event details can vary by Spring Boot version and application type.&lt;/p&gt;

&lt;p&gt;The important distinction is:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Context refreshed does not necessarily mean the application is fully ready.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The application may still need to execute startup runners and complete other readiness-related initialization.&lt;/p&gt;

&lt;p&gt;In a production environment, readiness should also account for the application's ability to serve requests safely.&lt;/p&gt;

&lt;p&gt;For example, a banking service may need to verify that essential dependencies are available before being marked ready.&lt;/p&gt;




&lt;h2&gt;
  
  
  13. Complete Spring Boot Startup Flow
&lt;/h2&gt;

&lt;p&gt;Let's summarize the entire lifecycle.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;main()
  |
  v
SpringApplication.run()
  |
  v
Create SpringApplication
  |
  v
Determine Application Type
  |
  v
Prepare Environment
  |
  v
Create ApplicationContext
  |
  v
Register Bean Definitions
  |
  v
Process Configuration Classes
  |
  v
Evaluate Auto-Configuration
  |
  v
ApplicationContext.refresh()
  |
  v
Create and Initialize Beans
  |
  v
Start Embedded Tomcat
  |
  v
ApplicationStartedEvent
  |
  v
Execute ApplicationRunner / CommandLineRunner
  |
  v
ApplicationReadyEvent
  |
  v
Application Ready
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fm1zr7xjw7a93dqqex10u.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fm1zr7xjw7a93dqqex10u.png" alt="Complete Spring Boot Startup Internals" width="799" height="408"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  14. Why Does Spring Boot Startup Sometimes Fail?
&lt;/h2&gt;

&lt;p&gt;Understanding the startup lifecycle helps us identify common failures.&lt;/p&gt;

&lt;h3&gt;
  
  
  BeanCreationException
&lt;/h3&gt;

&lt;p&gt;A bean cannot be created because of an invalid configuration or dependency.&lt;/p&gt;

&lt;h3&gt;
  
  
  NoSuchBeanDefinitionException
&lt;/h3&gt;

&lt;p&gt;Spring cannot find a required bean.&lt;/p&gt;

&lt;p&gt;Possible causes include missing component scanning, missing configuration, or an unavailable dependency.&lt;/p&gt;

&lt;h3&gt;
  
  
  Circular Dependency
&lt;/h3&gt;

&lt;p&gt;Two or more beans depend on each other in a way that prevents normal construction.&lt;/p&gt;

&lt;p&gt;Constructor-based circular dependencies generally fail during bean creation.&lt;/p&gt;

&lt;h3&gt;
  
  
  Port Already in Use
&lt;/h3&gt;

&lt;p&gt;The embedded server cannot bind to the configured port.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight properties"&gt;&lt;code&gt;&lt;span class="na"&gt;server.port&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;8080&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Another process may already be using that port.&lt;/p&gt;

&lt;h3&gt;
  
  
  Database Connection Failure
&lt;/h3&gt;

&lt;p&gt;The application may fail while initializing database infrastructure or connecting to a required database.&lt;/p&gt;

&lt;h3&gt;
  
  
  Auto-Configuration Conflict
&lt;/h3&gt;

&lt;p&gt;Multiple configurations may attempt to provide incompatible beans or infrastructure.&lt;/p&gt;

&lt;p&gt;The Spring Boot condition evaluation report can help identify why an auto-configuration was applied or skipped.&lt;/p&gt;

&lt;p&gt;Run the application with:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;java -jar banking-service.jar --debug
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The debug output can provide useful auto-configuration diagnostics.&lt;/p&gt;




&lt;h2&gt;
  
  
  15. Production Considerations for Spring Boot Startup
&lt;/h2&gt;

&lt;p&gt;In enterprise applications, startup behavior is not just a technical detail.&lt;/p&gt;

&lt;p&gt;It directly affects deployment reliability and service availability.&lt;/p&gt;

&lt;p&gt;Consider the following practices:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Keep startup initialization lightweight.&lt;/li&gt;
&lt;li&gt;Avoid unnecessary eager initialization of expensive resources.&lt;/li&gt;
&lt;li&gt;Use lazy initialization only when its trade-offs are understood.&lt;/li&gt;
&lt;li&gt;Externalize environment-specific configuration.&lt;/li&gt;
&lt;li&gt;Validate critical configuration early.&lt;/li&gt;
&lt;li&gt;Use readiness and liveness probes appropriately.&lt;/li&gt;
&lt;li&gt;Avoid blocking startup with long-running data loading.&lt;/li&gt;
&lt;li&gt;Monitor startup duration and initialization failures.&lt;/li&gt;
&lt;li&gt;Ensure essential downstream dependencies are available before readiness when required.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For Kubernetes and OpenShift deployments, startup probes, readiness probes, and liveness probes should be configured according to the application's actual startup and health behavior.&lt;/p&gt;

&lt;p&gt;A slow-starting application should not be repeatedly restarted simply because it needs additional time to initialize.&lt;/p&gt;




&lt;h2&gt;
  
  
  Final Thoughts
&lt;/h2&gt;

&lt;p&gt;Spring Boot simplifies application development, but internally it performs a sophisticated sequence of operations.&lt;/p&gt;

&lt;p&gt;From environment preparation and configuration processing to bean creation, dependency injection, embedded server startup, and application readiness, every phase plays an important role.&lt;/p&gt;

&lt;p&gt;Understanding this lifecycle helps Java developers:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Debug startup failures faster&lt;/li&gt;
&lt;li&gt;Understand dependency injection deeply&lt;/li&gt;
&lt;li&gt;Customize auto-configuration&lt;/li&gt;
&lt;li&gt;Improve startup performance&lt;/li&gt;
&lt;li&gt;Design reliable microservices&lt;/li&gt;
&lt;li&gt;Troubleshoot production deployments&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The next time you execute &lt;code&gt;SpringApplication.run()&lt;/code&gt;, remember that you are triggering the initialization of an entire application infrastructure — not just starting a Java program.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Spring Boot makes configuration easier, but understanding its internals makes you a better Spring Boot engineer.&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Author: Ram The Architect (RTA)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Follow me for more practical insights on Java 21 | Spring Boot | Microservices | Apache Kafka | AWS | System Design | GenAI&lt;/p&gt;

&lt;p&gt;Github: &lt;a href="https://github.com/Ramu-fsd/enterprise-banking-microservices" rel="noopener noreferrer"&gt;https://github.com/Ramu-fsd/enterprise-banking-microservices&lt;/a&gt;&lt;br&gt;
Linkedin: &lt;a href="https://www.linkedin.com/in/ramuboya/" rel="noopener noreferrer"&gt;https://www.linkedin.com/in/ramuboya/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Technology: Java 21 | Concurrency | Multithreading | CompletableFuture | Spring Boot | Microservices&lt;/p&gt;

&lt;h1&gt;
  
  
  Java #SpringBoot #SpringFramework #JavaDeveloper #Microservices #BackendDevelopment #SoftwareArchitecture #DevOps #Fintech
&lt;/h1&gt;

</description>
      <category>java</category>
      <category>springboot</category>
      <category>microservices</category>
      <category>softwaredevelopment</category>
    </item>
    <item>
      <title>CompletableFuture: Writing Asynchronous Java Applications</title>
      <dc:creator>Ramanjaneyulu Boya</dc:creator>
      <pubDate>Sun, 22 Nov 2026 07:48:32 +0000</pubDate>
      <link>https://dev.to/ramthearchitect/completablefuture-writing-asynchronous-java-applications-33f</link>
      <guid>https://dev.to/ramthearchitect/completablefuture-writing-asynchronous-java-applications-33f</guid>
      <description>&lt;p&gt;Modern enterprise applications need to handle thousands of concurrent requests while maintaining low response times and efficient resource utilization.&lt;/p&gt;

&lt;p&gt;Consider a banking application where a customer opens an account dashboard. The application may need to retrieve:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Account details&lt;/li&gt;
&lt;li&gt;Recent transactions&lt;/li&gt;
&lt;li&gt;Credit card information&lt;/li&gt;
&lt;li&gt;Loan details&lt;/li&gt;
&lt;li&gt;Fraud alerts&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Should the application call each service sequentially and wait for every response?&lt;/p&gt;

&lt;p&gt;Not necessarily.&lt;/p&gt;

&lt;p&gt;This is where Java's &lt;code&gt;CompletableFuture&lt;/code&gt; becomes extremely useful.&lt;/p&gt;

&lt;p&gt;Introduced in Java 8 and enhanced by subsequent Java releases, &lt;code&gt;CompletableFuture&lt;/code&gt; provides a powerful programming model for asynchronous and non-blocking task composition.&lt;/p&gt;

&lt;p&gt;In this article, we will explore how &lt;code&gt;CompletableFuture&lt;/code&gt; works, understand its important methods, and implement practical asynchronous workflows using Java 21.&lt;/p&gt;




&lt;h2&gt;
  
  
  1. What Is CompletableFuture?
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;CompletableFuture&lt;/code&gt; is an implementation of Java's &lt;code&gt;Future&lt;/code&gt; and &lt;code&gt;CompletionStage&lt;/code&gt; interfaces.&lt;/p&gt;

&lt;p&gt;It allows developers to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Execute tasks asynchronously.&lt;/li&gt;
&lt;li&gt;Retrieve results when computation completes.&lt;/li&gt;
&lt;li&gt;Chain multiple asynchronous operations.&lt;/li&gt;
&lt;li&gt;Execute independent tasks concurrently.&lt;/li&gt;
&lt;li&gt;Combine results from multiple asynchronous operations.&lt;/li&gt;
&lt;li&gt;Handle exceptions in asynchronous workflows.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Traditional synchronous execution blocks the calling thread until an operation completes.&lt;/p&gt;

&lt;p&gt;With asynchronous execution, the calling thread can continue performing other work while the task executes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;future&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
    &lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;supplyAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="s2"&gt;"Account details retrieved"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;future&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, &lt;code&gt;supplyAsync()&lt;/code&gt; executes the task asynchronously using the default ForkJoinPool common pool.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;join()&lt;/code&gt; retrieves the result and waits if necessary.&lt;/p&gt;




&lt;h2&gt;
  
  
  2. Synchronous vs Asynchronous Execution
&lt;/h2&gt;

&lt;p&gt;Consider retrieving customer information from three independent services.&lt;/p&gt;

&lt;h3&gt;
  
  
  Synchronous approach
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;Account&lt;/span&gt; &lt;span class="n"&gt;account&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;accountService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getAccount&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kt"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Transaction&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;transactions&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
    &lt;span class="n"&gt;transactionService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getTransactions&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kt"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Card&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;cards&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
    &lt;span class="n"&gt;cardService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getCards&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If each service takes 500 milliseconds, the approximate total execution time is:&lt;/p&gt;

&lt;p&gt;500 + 500 + 500 = 1500 milliseconds.&lt;/p&gt;

&lt;h3&gt;
  
  
  Asynchronous approach
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Account&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;accountFuture&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
    &lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;supplyAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;accountService&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;getAccount&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Transaction&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;transactionFuture&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
    &lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;supplyAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;transactionService&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;getTransactions&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Card&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;cardFuture&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
    &lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;supplyAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;cardService&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;getCards&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;allOf&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;accountFuture&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;transactionFuture&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;cardFuture&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The three independent operations can execute concurrently.&lt;/p&gt;

&lt;p&gt;If each takes approximately 500 milliseconds, total execution time may approach 500 milliseconds plus orchestration overhead, assuming sufficient resources.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Important:&lt;/strong&gt; Asynchronous execution does not automatically make operations faster. Actual performance depends on thread availability, service latency, connection pools, and system capacity.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F7z79n59so8grbxhejcwo.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F7z79n59so8grbxhejcwo.jpg" alt="SYNCHRONOUS VS ASYNCHRONOUS EXECUTION" width="800" height="410"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  3. Important CompletableFuture Methods
&lt;/h2&gt;

&lt;p&gt;Understanding the core methods is essential before implementing enterprise asynchronous applications.&lt;/p&gt;

&lt;h3&gt;
  
  
  3.1 runAsync()
&lt;/h3&gt;

&lt;p&gt;Use &lt;code&gt;runAsync()&lt;/code&gt; when a task does not return a result.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;Void&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;future&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
    &lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;runAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Sending notification..."&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="n"&gt;future&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Typical use cases:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Sending notifications&lt;/li&gt;
&lt;li&gt;Writing audit logs&lt;/li&gt;
&lt;li&gt;Triggering background tasks&lt;/li&gt;
&lt;li&gt;Updating non-critical metrics&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  3.2 supplyAsync()
&lt;/h3&gt;

&lt;p&gt;Use &lt;code&gt;supplyAsync()&lt;/code&gt; when a task returns a result.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;future&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
    &lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;supplyAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="s2"&gt;"Payment processed"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kt"&gt;String&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;future&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Typical use cases:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Fetching customer information&lt;/li&gt;
&lt;li&gt;Calling external APIs&lt;/li&gt;
&lt;li&gt;Retrieving transaction history&lt;/li&gt;
&lt;li&gt;Calculating risk scores&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  3.3 thenApply()
&lt;/h3&gt;

&lt;p&gt;Transforms the result of a completed computation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;future&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
    &lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;supplyAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="s2"&gt;"ramu"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;thenApply&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;toUpperCase&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;future&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;RAMU
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Think of &lt;code&gt;thenApply()&lt;/code&gt; as a transformation operation.&lt;/p&gt;

&lt;h3&gt;
  
  
  3.4 thenAccept()
&lt;/h3&gt;

&lt;p&gt;Consumes the result without returning another value.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;supplyAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="s2"&gt;"PAYMENT_SUCCESS"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;thenAccept&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Status: "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3.5 thenRun()
&lt;/h3&gt;

&lt;p&gt;Executes an operation after the previous stage completes, without consuming its result.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;supplyAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="s2"&gt;"ORDER_CREATED"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;thenRun&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Workflow completed"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  4. thenApply() vs thenCompose() vs thenCombine()
&lt;/h2&gt;

&lt;p&gt;This is one of the most frequently asked CompletableFuture interview topics.&lt;/p&gt;

&lt;h3&gt;
  
  
  thenApply()
&lt;/h3&gt;

&lt;p&gt;Transforms a result.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;future&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
    &lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;supplyAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="s2"&gt;"customer-101"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;thenApply&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;toUpperCase&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  thenCompose()
&lt;/h3&gt;

&lt;p&gt;Chains dependent asynchronous operations and flattens the resulting future.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Customer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;customerFuture&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
    &lt;span class="nf"&gt;getCustomerId&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;thenCompose&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;getCustomerDetails&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Without &lt;code&gt;thenCompose()&lt;/code&gt;, chaining a method that already returns a CompletableFuture can result in nested futures.&lt;/p&gt;

&lt;h3&gt;
  
  
  thenCombine()
&lt;/h3&gt;

&lt;p&gt;Combines two independent CompletableFuture results.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;Double&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;balanceFuture&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
    &lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;supplyAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="mf"&gt;50000.0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;Double&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;loanFuture&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
    &lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;supplyAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="mf"&gt;15000.0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;Double&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;totalFuture&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
    &lt;span class="n"&gt;balanceFuture&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;thenCombine&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;loanFuture&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="kt"&gt;Double&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;sum&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;totalFuture&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;65000.0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;When should you use them?&lt;/strong&gt;&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Method&lt;/th&gt;
&lt;th&gt;Purpose&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;thenApply()&lt;/td&gt;
&lt;td&gt;Transform a result&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;thenCompose()&lt;/td&gt;
&lt;td&gt;Chain dependent asynchronous tasks&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;thenCombine()&lt;/td&gt;
&lt;td&gt;Combine independent results&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fvuae72l4zd6hdpyspg74.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fvuae72l4zd6hdpyspg74.jpg" alt="COMPLETABLEFUTURE CHAINING METHODS" width="800" height="410"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  5. Combining Multiple Asynchronous Operations
&lt;/h2&gt;

&lt;p&gt;Enterprise applications frequently need data from multiple independent services.&lt;/p&gt;

&lt;p&gt;Consider a fintech dashboard.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Dashboard&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;getDashboard&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="kt"&gt;String&lt;/span&gt; &lt;span class="n"&gt;customerId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Account&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;accountFuture&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
        &lt;span class="n"&gt;accountService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getAccountAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;customerId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Transaction&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;transactionFuture&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
        &lt;span class="n"&gt;transactionService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getTransactionsAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;customerId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Card&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;cardFuture&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
        &lt;span class="n"&gt;cardService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getCardsAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;customerId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;allOf&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="n"&gt;accountFuture&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;transactionFuture&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;cardFuture&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;thenApply&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;ignored&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Dashboard&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="n"&gt;accountFuture&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;transactionFuture&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;cardFuture&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Account service executes asynchronously.&lt;/li&gt;
&lt;li&gt;Transaction service executes asynchronously.&lt;/li&gt;
&lt;li&gt;Card service executes asynchronously.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;allOf()&lt;/code&gt; waits for all futures to complete.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;thenApply()&lt;/code&gt; constructs the final dashboard.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Note that &lt;code&gt;allOf()&lt;/code&gt; returns &lt;code&gt;CompletableFuture&amp;lt;Void&amp;gt;&lt;/code&gt;. Individual results must be retrieved from their respective futures.&lt;/p&gt;

&lt;p&gt;This is a practical pattern for aggregating data from multiple microservices.&lt;/p&gt;

&lt;h3&gt;
  
  
  allOf() vs anyOf()
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;allOf():&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Waits for all supplied futures to complete.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;anyOf():&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Completes when any one of the supplied futures completes.&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;Object&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;fastest&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
    &lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;anyOf&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;service1Future&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;service2Future&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;service3Future&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This can be useful when implementing competing read strategies or fallback providers.&lt;/p&gt;

&lt;p&gt;However, &lt;code&gt;anyOf()&lt;/code&gt; does not automatically cancel the remaining tasks.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fp6ueugz15vhwnzbsa425.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fp6ueugz15vhwnzbsa425.jpg" alt="ALL OF VS ANY OF EXECUTION FLOW" width="800" height="409"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  6. Exception Handling in CompletableFuture
&lt;/h2&gt;

&lt;p&gt;Asynchronous applications must handle failures gracefully.&lt;/p&gt;

&lt;p&gt;What happens if an external banking service is unavailable?&lt;/p&gt;

&lt;p&gt;CompletableFuture provides several exception-handling methods.&lt;/p&gt;

&lt;h3&gt;
  
  
  exceptionally()
&lt;/h3&gt;

&lt;p&gt;Provides a fallback value when an exception occurs.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;future&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
    &lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;supplyAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;RuntimeException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Service unavailable"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;exceptionally&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;ex&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="s2"&gt;"DEFAULT_RESPONSE"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;future&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  handle()
&lt;/h3&gt;

&lt;p&gt;Handles both successful and exceptional completion.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;future&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
    &lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;supplyAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="s2"&gt;"SUCCESS"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;handle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;exception&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;exception&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="k"&gt;null&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="s2"&gt;"FAILED"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;

            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  whenComplete()
&lt;/h3&gt;

&lt;p&gt;Allows observation of the result or exception without transforming the outcome.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;future&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
    &lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;supplyAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="s2"&gt;"PAYMENT_SUCCESS"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;whenComplete&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;exception&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;exception&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="k"&gt;null&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;err&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;exception&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getMessage&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Key differences:&lt;/strong&gt;&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Method&lt;/th&gt;
&lt;th&gt;Purpose&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;exceptionally()&lt;/td&gt;
&lt;td&gt;Recover from an exception&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;handle()&lt;/td&gt;
&lt;td&gt;Transform success or failure&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;whenComplete()&lt;/td&gt;
&lt;td&gt;Observe completion&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;In financial applications, fallback behavior must be carefully designed. Never convert a failed payment verification into a successful payment response.&lt;/p&gt;




&lt;h2&gt;
  
  
  7. Custom Thread Pools with CompletableFuture
&lt;/h2&gt;

&lt;p&gt;By default, asynchronous methods such as &lt;code&gt;supplyAsync()&lt;/code&gt; use &lt;code&gt;ForkJoinPool.commonPool()&lt;/code&gt; when no executor is supplied.&lt;/p&gt;

&lt;p&gt;For production enterprise applications, using a dedicated executor is often preferable.&lt;/p&gt;

&lt;p&gt;Why?&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Better isolation between workloads.&lt;/li&gt;
&lt;li&gt;Predictable concurrency limits.&lt;/li&gt;
&lt;li&gt;Easier thread monitoring.&lt;/li&gt;
&lt;li&gt;Avoid interference between unrelated asynchronous tasks.&lt;/li&gt;
&lt;li&gt;Better control over resource utilization.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;ExecutorService&lt;/span&gt; &lt;span class="n"&gt;executor&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
    &lt;span class="nc"&gt;Executors&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;newFixedThreadPool&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;future&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
    &lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;supplyAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="s2"&gt;"Banking service response"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;executor&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can also define an executor using a &lt;code&gt;ThreadPoolExecutor&lt;/code&gt; for more explicit production configuration.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;ExecutorService&lt;/span&gt; &lt;span class="n"&gt;executor&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
    &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ThreadPoolExecutor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="mi"&gt;60&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="nc"&gt;TimeUnit&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;SECONDS&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;LinkedBlockingQueue&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Production considerations:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Configure bounded queues.&lt;/li&gt;
&lt;li&gt;Define appropriate rejection policies.&lt;/li&gt;
&lt;li&gt;Monitor active threads and queue utilization.&lt;/li&gt;
&lt;li&gt;Avoid unbounded task submission.&lt;/li&gt;
&lt;li&gt;Shut down executors gracefully.&lt;/li&gt;
&lt;li&gt;Size pools based on workload characteristics.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For blocking I/O workloads, thread-pool sizing should consider downstream latency and available resources.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F839d0u48gw7eq6ey2cl6.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F839d0u48gw7eq6ey2cl6.jpg" alt="COMPLETABLEFUTURE THREAD POOL ARCHITECTURE" width="800" height="409"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  8. CompletableFuture with Spring Boot
&lt;/h2&gt;

&lt;p&gt;Let's consider a practical Spring Boot example.&lt;/p&gt;

&lt;p&gt;A banking application needs to retrieve account information asynchronously.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;AccountService&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="nd"&gt;@Async&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"accountExecutor"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Account&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;getAccount&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="kt"&gt;String&lt;/span&gt; &lt;span class="n"&gt;accountId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

        &lt;span class="nc"&gt;Account&lt;/span&gt; &lt;span class="n"&gt;account&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;fetchAccountFromDatabase&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;accountId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;completedFuture&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;account&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Configure the executor:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Configuration&lt;/span&gt;
&lt;span class="nd"&gt;@EnableAsync&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;AsyncConfig&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="nd"&gt;@Bean&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"accountExecutor"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;Executor&lt;/span&gt; &lt;span class="nf"&gt;accountExecutor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

        &lt;span class="nc"&gt;ThreadPoolTaskExecutor&lt;/span&gt; &lt;span class="n"&gt;executor&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
            &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ThreadPoolTaskExecutor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="n"&gt;executor&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;setCorePoolSize&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="n"&gt;executor&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;setMaxPoolSize&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="n"&gt;executor&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;setQueueCapacity&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="n"&gt;executor&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;setThreadNamePrefix&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"account-"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="n"&gt;executor&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;initialize&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;executor&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Controller:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@RestController&lt;/span&gt;
&lt;span class="nd"&gt;@RequestMapping&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"/accounts"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;AccountController&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;AccountService&lt;/span&gt; &lt;span class="n"&gt;accountService&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;AccountController&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;AccountService&lt;/span&gt; &lt;span class="n"&gt;accountService&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;accountService&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;accountService&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@GetMapping&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"/{id}"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Account&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;getAccount&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="nd"&gt;@PathVariable&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;accountService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getAccount&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Spring MVC supports returning CompletableFuture from controller methods.&lt;/p&gt;

&lt;p&gt;The servlet request can be handled asynchronously while the computation executes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Important considerations:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;@Async&lt;/code&gt; works through Spring proxies; self-invocation does not trigger asynchronous interception.&lt;/li&gt;
&lt;li&gt;Configure exception handling and executor capacity.&lt;/li&gt;
&lt;li&gt;Avoid blocking operations on shared event-loop threads.&lt;/li&gt;
&lt;li&gt;Understand transaction boundaries when moving work across threads.&lt;/li&gt;
&lt;li&gt;Do not assume that asynchronous execution automatically improves database performance.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  9. CompletableFuture vs Future vs Java Virtual Threads
&lt;/h2&gt;

&lt;p&gt;Java developers should understand how these concurrency approaches differ.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Feature&lt;/th&gt;
&lt;th&gt;Future&lt;/th&gt;
&lt;th&gt;CompletableFuture&lt;/th&gt;
&lt;th&gt;Virtual Threads&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Asynchronous execution&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;Supports concurrent execution&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Result retrieval&lt;/td&gt;
&lt;td&gt;get()&lt;/td&gt;
&lt;td&gt;join(), get()&lt;/td&gt;
&lt;td&gt;Depends on task design&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Task chaining&lt;/td&gt;
&lt;td&gt;No built-in chaining&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;No built-in chaining&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Combining results&lt;/td&gt;
&lt;td&gt;Manual&lt;/td&gt;
&lt;td&gt;Built-in methods&lt;/td&gt;
&lt;td&gt;Manual or structured approach&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Exception handling&lt;/td&gt;
&lt;td&gt;Limited&lt;/td&gt;
&lt;td&gt;Rich API&lt;/td&gt;
&lt;td&gt;Standard exception handling&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Best suited for&lt;/td&gt;
&lt;td&gt;Basic asynchronous tasks&lt;/td&gt;
&lt;td&gt;Async workflows&lt;/td&gt;
&lt;td&gt;Large numbers of blocking tasks&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Virtual threads, introduced as a preview feature in Java 19 and finalized in Java 21, provide a lightweight threading model.&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ExecutorService&lt;/span&gt; &lt;span class="n"&gt;executor&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
         &lt;span class="nc"&gt;Executors&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;newVirtualThreadPerTaskExecutor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="nc"&gt;Future&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;future&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;executor&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;submit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="s2"&gt;"Account retrieved"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;future&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Use CompletableFuture when you need asynchronous composition and result coordination.&lt;/p&gt;

&lt;p&gt;Use virtual threads when you want straightforward thread-per-task programming, especially for blocking I/O workloads.&lt;/p&gt;

&lt;p&gt;They are complementary technologies, not direct replacements for each other.&lt;/p&gt;




&lt;h2&gt;
  
  
  10. Real-World Fintech Use Case: Payment Processing
&lt;/h2&gt;

&lt;p&gt;Consider a payment platform that needs to perform multiple independent operations:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Validate customer information.&lt;/li&gt;
&lt;li&gt;Retrieve merchant details.&lt;/li&gt;
&lt;li&gt;Perform fraud risk assessment.&lt;/li&gt;
&lt;li&gt;Retrieve transaction limits.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Some of these checks can execute concurrently.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;PaymentDecision&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;evaluatePayment&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="nc"&gt;PaymentRequest&lt;/span&gt; &lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Customer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;customerFuture&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
        &lt;span class="n"&gt;customerService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;validateAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Merchant&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;merchantFuture&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
        &lt;span class="n"&gt;merchantService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getMerchantAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;FraudResult&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;fraudFuture&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
        &lt;span class="n"&gt;fraudService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;evaluateAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;LimitResult&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;limitFuture&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
        &lt;span class="n"&gt;limitService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;checkAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;CompletableFuture&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;allOf&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="n"&gt;customerFuture&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;merchantFuture&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;fraudFuture&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;limitFuture&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;thenApply&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;ignored&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;paymentDecisionService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;evaluate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
                &lt;span class="n"&gt;customerFuture&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="n"&gt;merchantFuture&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="n"&gt;fraudFuture&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="n"&gt;limitFuture&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This approach reduces sequential waiting when the checks are independent.&lt;/p&gt;

&lt;p&gt;However, payment processing requires additional enterprise safeguards:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Define timeouts for external service calls.&lt;/li&gt;
&lt;li&gt;Apply circuit breakers and controlled retries.&lt;/li&gt;
&lt;li&gt;Preserve idempotency for payment requests.&lt;/li&gt;
&lt;li&gt;Handle partial failures explicitly.&lt;/li&gt;
&lt;li&gt;Maintain audit trails.&lt;/li&gt;
&lt;li&gt;Avoid treating unavailable fraud or limit services as successful checks.&lt;/li&gt;
&lt;li&gt;Separate authorization decisions from actual payment execution.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;CompletableFuture helps coordinate asynchronous operations. It does not replace distributed transaction management or payment consistency mechanisms.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fzxfu2cp6fvhzjnaetexs.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fzxfu2cp6fvhzjnaetexs.jpg" alt="FINTECH ASYNCHRONOUS PAYMENT ARCHITECTURE" width="800" height="410"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  11. Common Mistakes to Avoid
&lt;/h2&gt;

&lt;p&gt;When using CompletableFuture in production, watch out for these mistakes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Calling join() too early&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kt"&gt;String&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;future&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If called immediately after creating the future, you may lose the benefits of asynchronous composition.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Using the common pool for everything&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Different workloads may compete for shared worker threads.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Ignoring exception handling&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;An unhandled exceptional completion can cause failures to surface much later in the workflow.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Creating unbounded asynchronous tasks&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Too many concurrent operations can overwhelm downstream APIs, databases, and thread pools.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Ignoring timeouts&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Use &lt;code&gt;orTimeout()&lt;/code&gt; or &lt;code&gt;completeOnTimeout()&lt;/code&gt; where appropriate.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="n"&gt;future&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;orTimeout&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;TimeUnit&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;SECONDS&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;6. Assuming CompletableFuture guarantees non-blocking execution&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Methods such as &lt;code&gt;join()&lt;/code&gt; and &lt;code&gt;get()&lt;/code&gt; block the calling thread when the result is not ready. Also, asynchronous methods do not automatically make blocking I/O non-blocking.&lt;/p&gt;




&lt;h2&gt;
  
  
  12. Best Practices for Enterprise Applications
&lt;/h2&gt;

&lt;p&gt;For production-grade Java applications:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Prefer &lt;code&gt;thenApply()&lt;/code&gt; for transformations.&lt;/li&gt;
&lt;li&gt;Use &lt;code&gt;thenCompose()&lt;/code&gt; for dependent asynchronous operations.&lt;/li&gt;
&lt;li&gt;Use &lt;code&gt;thenCombine()&lt;/code&gt; for independent operations.&lt;/li&gt;
&lt;li&gt;Use &lt;code&gt;allOf()&lt;/code&gt; for coordinating multiple futures.&lt;/li&gt;
&lt;li&gt;Configure dedicated executors for workload isolation.&lt;/li&gt;
&lt;li&gt;Define timeouts for external service calls.&lt;/li&gt;
&lt;li&gt;Implement meaningful exception-handling strategies.&lt;/li&gt;
&lt;li&gt;Apply concurrency limits to protect downstream services.&lt;/li&gt;
&lt;li&gt;Monitor thread pools, queue sizes, latency, and failure rates.&lt;/li&gt;
&lt;li&gt;Consider virtual threads for suitable blocking workloads.&lt;/li&gt;
&lt;/ol&gt;




&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;CompletableFuture&lt;/code&gt; is one of the most powerful concurrency features available in modern Java.&lt;/p&gt;

&lt;p&gt;It enables developers to build asynchronous workflows, coordinate multiple independent operations, combine results, and handle failures without relying entirely on traditional blocking execution.&lt;/p&gt;

&lt;p&gt;For enterprise applications such as banking, payments, fraud detection, and customer platforms, understanding CompletableFuture is essential for building scalable and responsive systems.&lt;/p&gt;

&lt;p&gt;The real skill is not simply knowing how to call &lt;code&gt;supplyAsync()&lt;/code&gt; or &lt;code&gt;thenApply()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;It is knowing &lt;strong&gt;where to introduce concurrency, how to control resource utilization, and how to handle failures without compromising business correctness.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;That is what separates writing asynchronous code from designing production-ready asynchronous systems.&lt;/p&gt;




&lt;h2&gt;
  
  
  Interview Questions to Practice
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;What is CompletableFuture, and how is it different from Future?&lt;/li&gt;
&lt;li&gt;What is the difference between runAsync() and supplyAsync()?&lt;/li&gt;
&lt;li&gt;Explain thenApply() vs thenCompose() vs thenCombine().&lt;/li&gt;
&lt;li&gt;What is the difference between allOf() and anyOf()?&lt;/li&gt;
&lt;li&gt;How does CompletableFuture handle exceptions?&lt;/li&gt;
&lt;li&gt;What is the difference between exceptionally(), handle(), and whenComplete()?&lt;/li&gt;
&lt;li&gt;Which thread pool does CompletableFuture use by default?&lt;/li&gt;
&lt;li&gt;How do you configure a custom Executor?&lt;/li&gt;
&lt;li&gt;How do you implement timeout handling?&lt;/li&gt;
&lt;li&gt;Can CompletableFuture improve the performance of a Spring Boot microservice?&lt;/li&gt;
&lt;li&gt;What happens if one future in allOf() completes exceptionally?&lt;/li&gt;
&lt;li&gt;How does CompletableFuture compare with Java 21 Virtual Threads?&lt;/li&gt;
&lt;/ol&gt;




&lt;p&gt;&lt;strong&gt;Author:&lt;/strong&gt; Ram The Architect (RTA)&lt;/p&gt;

&lt;p&gt;Follow me for more practical insights on Java 21 | Spring Boot | Microservices | Apache Kafka | AWS | System Design | GenAI&lt;/p&gt;

&lt;p&gt;Github: &lt;a href="https://github.com/Ramu-fsd/enterprise-banking-microservices" rel="noopener noreferrer"&gt;https://github.com/Ramu-fsd/enterprise-banking-microservices&lt;/a&gt;&lt;br&gt;
Linkedin: &lt;a href="https://www.linkedin.com/in/ramuboya/" rel="noopener noreferrer"&gt;https://www.linkedin.com/in/ramuboya/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Technology:&lt;/strong&gt; Java 21 | Concurrency | Multithreading | CompletableFuture | Spring Boot | Microservices&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;#Java #Java21 #CompletableFuture #Multithreading #Concurrency #SpringBoot #Microservices #SoftwareArchitecture #Fintech #BackendDevelopment&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>java</category>
      <category>programming</category>
      <category>beginners</category>
      <category>softwaredevelopment</category>
    </item>
    <item>
      <title>HashMap vs LinkedHashMap vs TreeMap: Internal Differences, Performance and Real-World Use Cases</title>
      <dc:creator>Ramanjaneyulu Boya</dc:creator>
      <pubDate>Sun, 22 Nov 2026 03:43:19 +0000</pubDate>
      <link>https://dev.to/ramthearchitect/hashmap-vs-linkedhashmap-vs-treemap-internal-differences-performance-and-real-world-use-cases-bcd</link>
      <guid>https://dev.to/ramthearchitect/hashmap-vs-linkedhashmap-vs-treemap-internal-differences-performance-and-real-world-use-cases-bcd</guid>
      <description>&lt;p&gt;Java provides several Map implementations, but three of the most commonly used are &lt;code&gt;HashMap&lt;/code&gt;, &lt;code&gt;LinkedHashMap&lt;/code&gt;, and &lt;code&gt;TreeMap&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;At first glance, all three store data as key-value pairs. However, their internal implementations, ordering guarantees, performance characteristics, and real-world applications are significantly different.&lt;/p&gt;

&lt;p&gt;As a Java developer working on enterprise applications, understanding these differences is important—not just for writing code, but also for making the right architectural decisions.&lt;/p&gt;

&lt;p&gt;Consider a banking application:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Customer account details need fast lookups.&lt;/li&gt;
&lt;li&gt;Recent transactions should maintain insertion order.&lt;/li&gt;
&lt;li&gt;Transaction records may need to be sorted by transaction date.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Would you use the same Map implementation for all three scenarios?&lt;/p&gt;

&lt;p&gt;Probably not.&lt;/p&gt;

&lt;p&gt;Let's understand how these Map implementations work internally and when to use each one.&lt;/p&gt;




&lt;h2&gt;
  
  
  1. Understanding the Map Interface
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;Map&lt;/code&gt; interface stores data in key-value pairs.&lt;/p&gt;

&lt;p&gt;Each key must be unique, while multiple keys can have the same value.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kt"&gt;Map&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;Integer&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;customers&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;HashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="n"&gt;customers&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;101&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"John"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;customers&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;102&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"David"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;customers&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;103&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"Michael"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;customers&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;102&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;David
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Java provides multiple implementations of the Map interface, including:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;HashMap&lt;/li&gt;
&lt;li&gt;LinkedHashMap&lt;/li&gt;
&lt;li&gt;TreeMap&lt;/li&gt;
&lt;li&gt;Hashtable&lt;/li&gt;
&lt;li&gt;ConcurrentHashMap&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In this article, we will focus on HashMap, LinkedHashMap, and TreeMap.&lt;/p&gt;




&lt;h2&gt;
  
  
  2. HashMap: Fast Key-Value Lookups
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;HashMap&lt;/code&gt; is one of the most widely used Map implementations in Java.&lt;/p&gt;

&lt;p&gt;It provides average constant-time complexity for basic operations such as:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;put()&lt;/li&gt;
&lt;li&gt;get()&lt;/li&gt;
&lt;li&gt;remove()&lt;/li&gt;
&lt;li&gt;containsKey()&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Internal Architecture
&lt;/h3&gt;

&lt;p&gt;HashMap internally uses an array of buckets.&lt;/p&gt;

&lt;p&gt;Each bucket can contain:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A linked list of nodes.&lt;/li&gt;
&lt;li&gt;A balanced Red-Black Tree when collision handling reaches the treeification threshold and other conditions are satisfied.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Each node stores:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Node&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="no"&gt;K&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="no"&gt;V&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;hash&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="no"&gt;K&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="no"&gt;V&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nc"&gt;Node&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="no"&gt;K&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="no"&gt;V&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;next&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;How does HashMap store an entry?&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The key's &lt;code&gt;hashCode()&lt;/code&gt; is calculated.&lt;/li&gt;
&lt;li&gt;HashMap spreads the hash bits.&lt;/li&gt;
&lt;li&gt;The bucket index is calculated.&lt;/li&gt;
&lt;li&gt;The entry is stored in the corresponding bucket.&lt;/li&gt;
&lt;li&gt;If another key maps to the same bucket, collision handling takes place.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The simplified bucket-index calculation is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="n"&gt;index&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;capacity&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;hash&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Java uses a power-of-two table capacity to make this calculation efficient.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fgatj5zofz4hh2oyldl2g.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fgatj5zofz4hh2oyldl2g.jpg" alt="HashMap Internal Architecture" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Hash Collision Handling
&lt;/h3&gt;

&lt;p&gt;A collision occurs when multiple keys map to the same bucket.&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kt"&gt;Map&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;Integer&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;map&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;HashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="n"&gt;map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"Customer A"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;17&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"Customer B"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;33&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"Customer C"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Assuming a table capacity of 16, these integer keys map to the same bucket under the simplified index calculation.&lt;/p&gt;

&lt;p&gt;HashMap handles collisions using linked nodes.&lt;/p&gt;

&lt;p&gt;When collisions become sufficiently high, the bucket may be converted into a Red-Black Tree.&lt;/p&gt;

&lt;p&gt;Important Java 21 implementation details:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Default initial capacity: 16.&lt;/li&gt;
&lt;li&gt;Default load factor: 0.75.&lt;/li&gt;
&lt;li&gt;Treeification threshold: 8.&lt;/li&gt;
&lt;li&gt;Minimum capacity for treeification: 64.&lt;/li&gt;
&lt;li&gt;Untreeification threshold: 6.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;These are implementation details, not guarantees of the Map interface.&lt;/p&gt;

&lt;h3&gt;
  
  
  HashMap Performance
&lt;/h3&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Operation&lt;/th&gt;
&lt;th&gt;Average&lt;/th&gt;
&lt;th&gt;Worst case&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;get()&lt;/td&gt;
&lt;td&gt;O(1)&lt;/td&gt;
&lt;td&gt;O(n)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;put()&lt;/td&gt;
&lt;td&gt;O(1)&lt;/td&gt;
&lt;td&gt;O(n)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;remove()&lt;/td&gt;
&lt;td&gt;O(1)&lt;/td&gt;
&lt;td&gt;O(n)&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;With effective hashing and treeified collision buckets, collision-heavy lookups can achieve O(log n) behavior within those buckets.&lt;/p&gt;

&lt;h3&gt;
  
  
  Real-World Use Cases
&lt;/h3&gt;

&lt;p&gt;HashMap is suitable for:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Customer ID to customer details mapping.&lt;/li&gt;
&lt;li&gt;Product ID to product information.&lt;/li&gt;
&lt;li&gt;API response caching.&lt;/li&gt;
&lt;li&gt;Configuration properties.&lt;/li&gt;
&lt;li&gt;Frequently accessed reference data.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kt"&gt;Map&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Customer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;customerCache&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;HashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="n"&gt;customerCache&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"CUST101"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;customer&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nc"&gt;Customer&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;customerCache&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"CUST101"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;When should you use HashMap?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When fast key-based lookup is your primary requirement and you do not need ordering.&lt;/p&gt;




&lt;h2&gt;
  
  
  3. LinkedHashMap: Maintaining Insertion Order
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;LinkedHashMap&lt;/code&gt; extends &lt;code&gt;HashMap&lt;/code&gt; and maintains a doubly linked list across its entries.&lt;/p&gt;

&lt;p&gt;Unlike HashMap, it provides predictable iteration order.&lt;/p&gt;

&lt;p&gt;By default, that order is insertion order.&lt;/p&gt;

&lt;h3&gt;
  
  
  Internal Architecture
&lt;/h3&gt;

&lt;p&gt;LinkedHashMap maintains:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Hash table for fast key lookup.&lt;/li&gt;
&lt;li&gt;Doubly linked list for maintaining entry order.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Each entry maintains additional references:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="n"&gt;before&lt;/span&gt;
&lt;span class="n"&gt;after&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;These references connect entries in insertion order.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fp6mzs7ygeunuqh3k6nfk.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fp6mzs7ygeunuqh3k6nfk.jpg" alt="LinkedHashMap Internal Architecture" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Example
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kt"&gt;Map&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;Integer&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;map&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;LinkedHashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="n"&gt;map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;103&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"Michael"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;101&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"John"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;102&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"David"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="n"&gt;map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;forEach&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;
    &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s2"&gt;" : "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;103 : Michael
101 : John
102 : David
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notice that entries are returned in insertion order.&lt;/p&gt;

&lt;h3&gt;
  
  
  Access-Order LinkedHashMap
&lt;/h3&gt;

&lt;p&gt;One interesting feature of LinkedHashMap is that it supports access-order iteration.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;LinkedHashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;Integer&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;map&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
    &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;LinkedHashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;16&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mf"&gt;0.75f&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="n"&gt;map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;101&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"John"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;102&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"David"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;103&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"Michael"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="n"&gt;map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;101&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="n"&gt;map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;forEach&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;
    &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s2"&gt;" : "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;102 : David
103 : Michael
101 : John
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The accessed entry moves to the end of the iteration order.&lt;/p&gt;

&lt;p&gt;This feature is particularly useful when implementing an LRU (Least Recently Used) cache.&lt;/p&gt;

&lt;h3&gt;
  
  
  Implementing an LRU Cache
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;LRUCache&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="no"&gt;K&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;V&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="k"&gt;extends&lt;/span&gt; &lt;span class="nc"&gt;LinkedHashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="no"&gt;K&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;V&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;capacity&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;LRUCache&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;capacity&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;super&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;16&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mf"&gt;0.75f&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;capacity&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;capacity&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@Override&lt;/span&gt;
    &lt;span class="k"&gt;protected&lt;/span&gt; &lt;span class="kt"&gt;boolean&lt;/span&gt; &lt;span class="nf"&gt;removeEldestEntry&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="kt"&gt;Map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Entry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="no"&gt;K&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;V&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;eldest&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;size&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;capacity&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Usage:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;LRUCache&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;Integer&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;cache&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;LRUCache&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="n"&gt;cache&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"Customer A"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;cache&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"Customer B"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;cache&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"Customer C"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="n"&gt;cache&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="n"&gt;cache&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"Customer D"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cache&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Entry 2 is removed because it is the least recently accessed entry.&lt;/p&gt;

&lt;p&gt;Note: This example is not thread-safe. Production cache implementations need appropriate concurrency controls or a dedicated caching solution.&lt;/p&gt;

&lt;h3&gt;
  
  
  LinkedHashMap Performance
&lt;/h3&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Operation&lt;/th&gt;
&lt;th&gt;Average&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;get()&lt;/td&gt;
&lt;td&gt;O(1)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;put()&lt;/td&gt;
&lt;td&gt;O(1)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;remove()&lt;/td&gt;
&lt;td&gt;O(1)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Iteration&lt;/td&gt;
&lt;td&gt;O(n)&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;It has additional memory overhead because every entry maintains linked-list references.&lt;/p&gt;

&lt;h3&gt;
  
  
  Real-World Use Cases
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;LRU cache implementation.&lt;/li&gt;
&lt;li&gt;Maintaining API response insertion order.&lt;/li&gt;
&lt;li&gt;Ordered transaction processing.&lt;/li&gt;
&lt;li&gt;Maintaining predictable configuration output.&lt;/li&gt;
&lt;li&gt;Recently accessed customer or product records.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;When should you use LinkedHashMap?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When you need HashMap-like lookup performance along with predictable iteration order.&lt;/p&gt;




&lt;h2&gt;
  
  
  4. TreeMap: Maintaining Sorted Order
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;TreeMap&lt;/code&gt; is different from HashMap and LinkedHashMap.&lt;/p&gt;

&lt;p&gt;It internally uses a Red-Black Tree, which is a self-balancing binary search tree.&lt;/p&gt;

&lt;p&gt;Unlike the previous implementations, TreeMap maintains its keys in sorted order.&lt;/p&gt;

&lt;p&gt;By default, keys are sorted using their natural ordering. You can also provide a custom Comparator.&lt;/p&gt;

&lt;h3&gt;
  
  
  Internal Architecture
&lt;/h3&gt;

&lt;p&gt;A Red-Black Tree maintains balance through:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Node coloring.&lt;/li&gt;
&lt;li&gt;Left and right rotations.&lt;/li&gt;
&lt;li&gt;Recoloring during insertion and deletion.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;These mechanisms prevent the tree from becoming excessively unbalanced.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Flzvwypr5n64lh6bdlc6h.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Flzvwypr5n64lh6bdlc6h.jpg" alt="TreeMap Red-Black Tree Architecture" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Example
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kt"&gt;Map&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;Integer&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;map&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;TreeMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="n"&gt;map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;103&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"Michael"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;101&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"John"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;102&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"David"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="n"&gt;map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;forEach&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;
    &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s2"&gt;" : "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;101 : John
102 : David
103 : Michael
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Even though entries were inserted in a different order, TreeMap maintains sorted key order.&lt;/p&gt;

&lt;h3&gt;
  
  
  Custom Sorting with Comparator
&lt;/h3&gt;

&lt;p&gt;Suppose a banking application needs to sort transactions based on transaction amount.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kt"&gt;Map&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;Double&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;transactions&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
    &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;TreeMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Comparator&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;reverseOrder&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="n"&gt;transactions&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mf"&gt;5000.0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"Payment A"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;transactions&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mf"&gt;1500.0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"Payment B"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;transactions&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mf"&gt;9000.0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"Payment C"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;transactions&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{9000.0=Payment C, 5000.0=Payment A, 1500.0=Payment B}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Important: TreeMap uses key comparison to determine key uniqueness. Two keys for which the comparator returns zero are treated as the same key.&lt;/p&gt;

&lt;p&gt;For real financial applications, avoid using floating-point values as monetary keys. Prefer BigDecimal with a carefully defined comparator, or use a unique transaction ID as the key and sort transaction objects separately.&lt;/p&gt;

&lt;h3&gt;
  
  
  NavigableMap Features
&lt;/h3&gt;

&lt;p&gt;TreeMap implements NavigableMap, providing useful methods:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;TreeMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;Integer&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;map&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;TreeMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="n"&gt;map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"A"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;200&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"B"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;300&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"C"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;400&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"D"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;firstKey&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;lastKey&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;lowerKey&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;300&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;higherKey&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;300&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;floorKey&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;250&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;ceilingKey&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;250&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;100
400
200
400
200
300
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;These methods are especially useful for range-based queries.&lt;/p&gt;

&lt;h3&gt;
  
  
  TreeMap Performance
&lt;/h3&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Operation&lt;/th&gt;
&lt;th&gt;Complexity&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;get()&lt;/td&gt;
&lt;td&gt;O(log n)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;put()&lt;/td&gt;
&lt;td&gt;O(log n)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;remove()&lt;/td&gt;
&lt;td&gt;O(log n)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;firstKey()&lt;/td&gt;
&lt;td&gt;O(log n)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;lastKey()&lt;/td&gt;
&lt;td&gt;O(log n)&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h3&gt;
  
  
  Real-World Use Cases
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Maintaining transactions by timestamp.&lt;/li&gt;
&lt;li&gt;Sorting customer records by account number.&lt;/li&gt;
&lt;li&gt;Price-based product ordering.&lt;/li&gt;
&lt;li&gt;Range-based searches.&lt;/li&gt;
&lt;li&gt;Scheduling events by execution time.&lt;/li&gt;
&lt;li&gt;Finding the nearest available time slot.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;When should you use TreeMap?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When sorted keys, range queries, or navigation operations are important.&lt;/p&gt;




&lt;h2&gt;
  
  
  5. HashMap vs LinkedHashMap vs TreeMap
&lt;/h2&gt;

&lt;p&gt;Let's compare all three implementations.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Feature&lt;/th&gt;
&lt;th&gt;HashMap&lt;/th&gt;
&lt;th&gt;LinkedHashMap&lt;/th&gt;
&lt;th&gt;TreeMap&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Internal structure&lt;/td&gt;
&lt;td&gt;Hash table&lt;/td&gt;
&lt;td&gt;Hash table + doubly linked list&lt;/td&gt;
&lt;td&gt;Red-Black Tree&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Ordering&lt;/td&gt;
&lt;td&gt;No guarantee&lt;/td&gt;
&lt;td&gt;Insertion/access order&lt;/td&gt;
&lt;td&gt;Sorted key order&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;get()&lt;/td&gt;
&lt;td&gt;O(1) average&lt;/td&gt;
&lt;td&gt;O(1) average&lt;/td&gt;
&lt;td&gt;O(log n)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;put()&lt;/td&gt;
&lt;td&gt;O(1) average&lt;/td&gt;
&lt;td&gt;O(1) average&lt;/td&gt;
&lt;td&gt;O(log n)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;remove()&lt;/td&gt;
&lt;td&gt;O(1) average&lt;/td&gt;
&lt;td&gt;O(1) average&lt;/td&gt;
&lt;td&gt;O(log n)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Null key&lt;/td&gt;
&lt;td&gt;One allowed&lt;/td&gt;
&lt;td&gt;One allowed&lt;/td&gt;
&lt;td&gt;Generally not allowed with natural ordering&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Null values&lt;/td&gt;
&lt;td&gt;Allowed&lt;/td&gt;
&lt;td&gt;Allowed&lt;/td&gt;
&lt;td&gt;Allowed&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Memory overhead&lt;/td&gt;
&lt;td&gt;Lower&lt;/td&gt;
&lt;td&gt;Higher&lt;/td&gt;
&lt;td&gt;Higher&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Thread-safe&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Remember: HashMap and LinkedHashMap do not guarantee constant-time operations in every situation. Their performance depends on hash distribution and resizing behavior.&lt;/p&gt;




&lt;h2&gt;
  
  
  6. Real-World Banking Application: Choosing the Right Map
&lt;/h2&gt;

&lt;p&gt;Let's consider a fintech platform with three requirements.&lt;/p&gt;

&lt;h3&gt;
  
  
  Scenario 1: Customer Lookup
&lt;/h3&gt;

&lt;p&gt;Requirement:&lt;/p&gt;

&lt;p&gt;Retrieve customer information quickly using customer ID.&lt;/p&gt;

&lt;p&gt;Recommended implementation: HashMap.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kt"&gt;Map&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Customer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;customerMap&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;HashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="n"&gt;customerMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"C101"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;customer&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nc"&gt;Customer&lt;/span&gt; &lt;span class="n"&gt;customer&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;customerMap&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"C101"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Reason: Fast key-based lookups without ordering requirements.&lt;/p&gt;

&lt;h3&gt;
  
  
  Scenario 2: Recently Accessed Accounts
&lt;/h3&gt;

&lt;p&gt;Requirement:&lt;/p&gt;

&lt;p&gt;Maintain recently accessed customer accounts in access order and remove older entries when the cache reaches its capacity.&lt;/p&gt;

&lt;p&gt;Recommended implementation: LinkedHashMap.&lt;/p&gt;

&lt;p&gt;Reason: Access-order iteration and eldest-entry removal support LRU cache implementation.&lt;/p&gt;

&lt;h3&gt;
  
  
  Scenario 3: Transactions Sorted by Timestamp
&lt;/h3&gt;

&lt;p&gt;Requirement:&lt;/p&gt;

&lt;p&gt;Maintain transaction records in timestamp order and retrieve transactions within a date range.&lt;/p&gt;

&lt;p&gt;Recommended implementation: TreeMap.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;NavigableMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;LocalDateTime&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Transaction&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;transactions&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
    &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;TreeMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="n"&gt;transactions&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="nc"&gt;LocalDateTime&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;now&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;transaction&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Range query:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;NavigableMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;LocalDateTime&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Transaction&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;dailyTransactions&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
    &lt;span class="n"&gt;transactions&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;subMap&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;startTime&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;endTime&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Reason: Sorted keys and efficient range navigation.&lt;/p&gt;

&lt;p&gt;Production consideration: If multiple transactions can share the same timestamp, a TreeMap keyed only by timestamp will overwrite earlier entries. Use a composite key or another collection strategy to preserve every transaction.&lt;/p&gt;




&lt;h2&gt;
  
  
  7. Important Internal Concepts Every Java Developer Should Know
&lt;/h2&gt;

&lt;p&gt;Understanding these concepts helps explain the performance differences during technical interviews.&lt;/p&gt;

&lt;h3&gt;
  
  
  A. Hashing and hashCode()
&lt;/h3&gt;

&lt;p&gt;HashMap uses hashCode() to identify the bucket where an entry should be stored.&lt;/p&gt;

&lt;p&gt;The equals() method determines whether two keys are logically equal.&lt;/p&gt;

&lt;p&gt;The contract is important:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If two objects are equal according to equals(), they must have the same hashCode().&lt;/li&gt;
&lt;li&gt;Different objects may have the same hashCode().&lt;/li&gt;
&lt;li&gt;hashCode() does not guarantee uniqueness.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  B. Resizing and Load Factor
&lt;/h3&gt;

&lt;p&gt;HashMap and LinkedHashMap resize when the number of entries exceeds their threshold.&lt;/p&gt;

&lt;p&gt;Default configuration:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="n"&gt;capacity&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;16&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;loadFactor&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;0.75&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="n"&gt;threshold&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;capacity&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;loadFactor&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Therefore:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;16 * 0.75 = 12
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When the threshold is exceeded, the table is resized, generally doubling its capacity.&lt;/p&gt;

&lt;p&gt;Resizing involves redistributing entries into the new table.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Flnjlusn0qiybuebsymmu.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Flnjlusn0qiybuebsymmu.jpg" alt="HashMap Resizing" width="800" height="451"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  C. Why TreeMap Does Not Need Hashing
&lt;/h3&gt;

&lt;p&gt;TreeMap does not use hashCode().&lt;/p&gt;

&lt;p&gt;It relies on key comparison using:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Comparable&lt;/li&gt;
&lt;li&gt;Comparator&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is why TreeMap can maintain sorted key order without calculating hash buckets.&lt;/p&gt;

&lt;h3&gt;
  
  
  D. Thread Safety
&lt;/h3&gt;

&lt;p&gt;None of these three Map implementations is inherently thread-safe.&lt;/p&gt;

&lt;p&gt;For concurrent applications, consider:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kt"&gt;Map&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Customer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;customerMap&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
    &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ConcurrentHashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;ConcurrentHashMap supports concurrent access and updates.&lt;/p&gt;

&lt;p&gt;For a synchronized wrapper:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kt"&gt;Map&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Customer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;synchronizedMap&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
    &lt;span class="nc"&gt;Collections&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;synchronizedMap&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;HashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Remember that compound operations and iteration still require appropriate synchronization.&lt;/p&gt;




&lt;h2&gt;
  
  
  8. Common Interview Questions
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Q1. Why is HashMap faster than TreeMap?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;HashMap provides average O(1) lookup using hashing, whereas TreeMap uses a Red-Black Tree and provides O(log n) lookup.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Q2. Does LinkedHashMap maintain insertion order?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Yes. By default, it maintains insertion order. It can also maintain access order using its constructor parameter.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Q3. How does HashMap handle collisions?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It uses linked nodes within buckets and can convert heavily populated buckets into Red-Black Trees when the required conditions are met.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Q4. Can TreeMap contain null keys?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;With natural ordering, null keys are not supported. A custom comparator may support null if it explicitly handles them.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Q5. Why is TreeMap useful for range queries?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It implements NavigableMap, which provides methods such as subMap(), headMap(), tailMap(), floorKey(), and ceilingKey().&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Q6. Is LinkedHashMap suitable for implementing an LRU cache?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Yes. Its access-order mode and removeEldestEntry() method make it a convenient starting point for a simple LRU cache.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Q7. What happens when two HashMap keys have the same hashCode()?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;They are placed in the same bucket. HashMap uses equals() to distinguish them.&lt;/p&gt;




&lt;h2&gt;
  
  
  9. Final Thoughts
&lt;/h2&gt;

&lt;p&gt;Choosing a Map implementation is not just about knowing Java Collections. It is about understanding application requirements and making the right engineering trade-offs.&lt;/p&gt;

&lt;p&gt;My recommendation:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Use HashMap when fast key-based lookups are the priority.&lt;/li&gt;
&lt;li&gt;Use LinkedHashMap when predictable iteration order or simple LRU behavior is required.&lt;/li&gt;
&lt;li&gt;Use TreeMap when sorted keys and range-based operations are important.&lt;/li&gt;
&lt;li&gt;Use ConcurrentHashMap when concurrent access is required.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In enterprise applications, selecting the correct collection can improve performance, simplify implementation, and make the code easier to maintain.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;A good Java developer knows how to use collections. A strong engineer knows why a particular collection is the right choice for a particular problem.&lt;/strong&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Java Collections are fundamental to building scalable backend applications.&lt;/p&gt;

&lt;p&gt;Understanding their internal data structures, complexity, memory overhead, and operational trade-offs helps developers write better production code.&lt;/p&gt;

&lt;p&gt;Keep exploring. Keep building. Keep architecting.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ram The Architect (RTA)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Follow me for more practical insights on Java 21 | Spring Boot | Microservices | Apache Kafka | AWS | System Design | GenAI&lt;/p&gt;

&lt;p&gt;Github: &lt;a href="https://github.com/Ramu-fsd/" rel="noopener noreferrer"&gt;https://github.com/Ramu-fsd/&lt;/a&gt;&lt;br&gt;
Linkedin: &lt;a href="https://www.linkedin.com/in/ramuboya/" rel="noopener noreferrer"&gt;https://www.linkedin.com/in/ramuboya/&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  References
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Java 21 HashMap Documentation: &lt;a href="https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/HashMap.html" rel="noopener noreferrer"&gt;https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/HashMap.html&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Java 21 LinkedHashMap Documentation: &lt;a href="https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/LinkedHashMap.html" rel="noopener noreferrer"&gt;https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/LinkedHashMap.html&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Java 21 TreeMap Documentation: &lt;a href="https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/TreeMap.html" rel="noopener noreferrer"&gt;https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/TreeMap.html&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Java Collections Framework: &lt;a href="https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/package-summary.html" rel="noopener noreferrer"&gt;https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/package-summary.html&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  Java #Java21 #CoreJava #JavaCollections #HashMap #LinkedHashMap #TreeMap #BackendDevelopment #SoftwareArchitecture #SystemDesign #Programming
&lt;/h1&gt;

</description>
      <category>java</category>
      <category>programming</category>
      <category>beginners</category>
      <category>architecture</category>
    </item>
    <item>
      <title>How Java HashMap Works Internally: Hashing, Buckets, Collisions, Resizing and Performance</title>
      <dc:creator>Ramanjaneyulu Boya</dc:creator>
      <pubDate>Thu, 19 Nov 2026 17:47:42 +0000</pubDate>
      <link>https://dev.to/ramthearchitect/how-java-hashmap-works-internally-hashing-buckets-collisions-resizing-and-performance-53mk</link>
      <guid>https://dev.to/ramthearchitect/how-java-hashmap-works-internally-hashing-buckets-collisions-resizing-and-performance-53mk</guid>
      <description>&lt;p&gt;&lt;strong&gt;Understanding the internal implementation of HashMap is essential for every Java developer, especially when building high-performance backend applications and microservices.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We use &lt;code&gt;HashMap&lt;/code&gt; almost everywhere in Java applications.&lt;/p&gt;

&lt;p&gt;Whether we are caching API responses, storing configuration properties, processing transactions, maintaining session data, or building in-memory lookup structures, HashMap is one of the most frequently used data structures.&lt;/p&gt;

&lt;p&gt;But have you ever wondered:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;How does HashMap store key-value pairs internally?&lt;/li&gt;
&lt;li&gt;How does it identify the bucket for a particular key?&lt;/li&gt;
&lt;li&gt;What happens when two keys generate the same hash?&lt;/li&gt;
&lt;li&gt;How does HashMap handle collisions?&lt;/li&gt;
&lt;li&gt;Why does HashMap resize automatically?&lt;/li&gt;
&lt;li&gt;Why does Java 8 introduce Red-Black Trees inside HashMap?&lt;/li&gt;
&lt;li&gt;What makes HashMap operations approximately O(1)?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let's understand the internal implementation step by step, using Java 21 examples.&lt;/p&gt;




&lt;h2&gt;
  
  
  1. What Is HashMap?
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;HashMap&lt;/code&gt; is a part of the Java Collections Framework and implements the &lt;code&gt;Map&lt;/code&gt; interface.&lt;/p&gt;

&lt;p&gt;It stores data in key-value pairs.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kt"&gt;Map&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;Integer&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;employees&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;HashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="n"&gt;employees&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;101&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"John"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;employees&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;102&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"David"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;employees&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;103&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"Michael"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;employees&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;102&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;David
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Unlike a List, HashMap does not maintain insertion order.&lt;/p&gt;

&lt;p&gt;Important characteristics:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Stores key-value pairs.&lt;/li&gt;
&lt;li&gt;Allows one null key.&lt;/li&gt;
&lt;li&gt;Allows multiple null values.&lt;/li&gt;
&lt;li&gt;Does not guarantee iteration order.&lt;/li&gt;
&lt;li&gt;Is not thread-safe.&lt;/li&gt;
&lt;li&gt;Provides approximately O(1) average-time performance for basic operations.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;But internally, how does it achieve this performance?&lt;/p&gt;

&lt;p&gt;Let's explore.&lt;/p&gt;




&lt;h2&gt;
  
  
  2. Internal Data Structure of HashMap
&lt;/h2&gt;

&lt;p&gt;Internally, HashMap uses an array of nodes.&lt;/p&gt;

&lt;p&gt;Each node stores:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Hash&lt;/li&gt;
&lt;li&gt;Key&lt;/li&gt;
&lt;li&gt;Value&lt;/li&gt;
&lt;li&gt;Reference to the next node&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The simplified internal structure looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Node&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="no"&gt;K&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="no"&gt;V&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="k"&gt;implements&lt;/span&gt; &lt;span class="kt"&gt;Map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Entry&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="no"&gt;K&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="no"&gt;V&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;hash&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="no"&gt;K&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="no"&gt;V&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nc"&gt;Node&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="no"&gt;K&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="no"&gt;V&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;next&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The important field here is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;Node&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="no"&gt;K&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="no"&gt;V&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="n"&gt;table&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is the internal bucket array.&lt;/p&gt;

&lt;p&gt;Each array position represents a bucket, and each bucket can contain one or more entries.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fu5upkdid1a5cj8sfwk4f.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fu5upkdid1a5cj8sfwk4f.jpg" alt="HASHMAP INTERNAL DATA STRUCTURE" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  3. How HashMap Calculates the Hash
&lt;/h2&gt;

&lt;p&gt;When we insert an entry using &lt;code&gt;put()&lt;/code&gt;, HashMap first calculates the hash of the key.&lt;/p&gt;

&lt;p&gt;Simplified Java 8+ implementation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;hash&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;Object&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;h&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="k"&gt;null&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="o"&gt;?&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
            &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;h&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;hashCode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;^&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;h&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;16&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's understand this expression:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="n"&gt;h&lt;/span&gt; &lt;span class="o"&gt;^&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;h&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;16&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;h&lt;/code&gt; represents the original hashCode.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/code&gt; performs an unsigned right shift.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;^&lt;/code&gt; represents the bitwise XOR operation.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Why does HashMap perform this additional calculation?&lt;/p&gt;

&lt;p&gt;Because Java hashCode is a 32-bit integer, but HashMap uses a power-of-two-sized array to determine the bucket index.&lt;/p&gt;

&lt;p&gt;The index calculation uses the lower bits of the hash.&lt;/p&gt;

&lt;p&gt;By XORing the upper 16 bits with the lower 16 bits, HashMap helps distribute information from the higher bits into the lower bits.&lt;/p&gt;

&lt;p&gt;This improves hash distribution in many cases.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Important:&lt;/strong&gt; Hash spreading does not eliminate collisions. It helps reduce poor distribution.&lt;/p&gt;




&lt;h2&gt;
  
  
  4. How HashMap Calculates the Bucket Index
&lt;/h2&gt;

&lt;p&gt;After calculating the hash, HashMap determines where the entry should be stored.&lt;/p&gt;

&lt;p&gt;The bucket index is calculated using:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="n"&gt;index&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;hash&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Where:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;n&lt;/code&gt; is the capacity of the internal array.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;hash&lt;/code&gt; is the spread hash value.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;&amp;amp;&lt;/code&gt; is the bitwise AND operator.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Why not use the modulo operator?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="n"&gt;index&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;hash&lt;/span&gt; &lt;span class="o"&gt;%&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;HashMap uses bitwise AND because its capacity is always a power of two.&lt;/p&gt;

&lt;p&gt;For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Capacity = 16

n - 1 = 15

15 in binary = 00001111
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The operation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="n"&gt;index&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;hash&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;is efficient and selects the bucket using the lower bits.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Capacity = 16
Hash = 35

Index = (16 - 1) &amp;amp; 35

Index = 15 &amp;amp; 35

Index = 3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Therefore, the entry is stored in bucket index 3.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fq1hq76oyyfq4nlnjfqfo.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fq1hq76oyyfq4nlnjfqfo.jpg" alt="HASHING AND BUCKET INDEX CALCULATION" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  5. What Happens When Two Keys Have the Same Hash?
&lt;/h2&gt;

&lt;p&gt;This is called a hash collision.&lt;/p&gt;

&lt;p&gt;Consider:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kt"&gt;Map&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;map&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;HashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="n"&gt;map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Aa"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"BB"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;200&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Interestingly:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Aa"&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;hashCode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"BB"&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;hashCode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Both produce the same hashCode:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;2112
2112
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Both entries are directed to the same bucket.&lt;/p&gt;

&lt;p&gt;Does HashMap overwrite the existing value?&lt;/p&gt;

&lt;p&gt;No.&lt;/p&gt;

&lt;p&gt;HashMap handles collisions by storing multiple entries in the same bucket.&lt;/p&gt;

&lt;p&gt;In Java 8 and later, the bucket initially uses a linked list.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Bucket 3

  Node("Aa", 100)
          |
          v
  Node("BB", 200)
          |
          v
        null
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When retrieving a value, HashMap:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Calculates the hash of the key.&lt;/li&gt;
&lt;li&gt;Identifies the bucket.&lt;/li&gt;
&lt;li&gt;Compares the hash.&lt;/li&gt;
&lt;li&gt;Checks key equality using reference equality or &lt;code&gt;equals()&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Returns the matching value.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This is why implementing &lt;code&gt;equals()&lt;/code&gt; and &lt;code&gt;hashCode()&lt;/code&gt; correctly is extremely important.&lt;/p&gt;




&lt;h2&gt;
  
  
  6. How HashMap Handles Collisions: Linked List to Red-Black Tree
&lt;/h2&gt;

&lt;p&gt;This is one of the most important improvements introduced in Java 8.&lt;/p&gt;

&lt;p&gt;Before Java 8, HashMap used linked lists to handle collisions.&lt;/p&gt;

&lt;p&gt;In a heavily populated bucket, searching could degrade to O(n).&lt;/p&gt;

&lt;p&gt;Java 8 introduced a mechanism called &lt;strong&gt;Treeification&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;When a bucket contains too many entries, HashMap can convert its linked list into a Red-Black Tree.&lt;/p&gt;

&lt;p&gt;Important implementation constants:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="no"&gt;TREEIFY_THRESHOLD&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="no"&gt;UNTREEIFY_THRESHOLD&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="no"&gt;MIN_TREEIFY_CAPACITY&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;64&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's understand them.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;TREEIFY_THRESHOLD = 8&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When a bucket reaches the treeification threshold, HashMap may convert the linked list into a Red-Black Tree.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;MIN_TREEIFY_CAPACITY = 64&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If the overall HashMap capacity is below 64, HashMap prefers resizing the table instead of treeifying the bucket.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;UNTREEIFY_THRESHOLD = 6&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;During resizing, a tree bin can convert back into a linked list when its population becomes sufficiently small.&lt;/p&gt;

&lt;p&gt;Why use a Red-Black Tree?&lt;/p&gt;

&lt;p&gt;Because searching a balanced tree takes approximately O(log n), compared with O(n) for a linked list.&lt;/p&gt;

&lt;p&gt;The actual implementation has additional details, including collision distribution and tree balancing.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fhi3k5i31d0ksqo7td44v.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fhi3k5i31d0ksqo7td44v.jpg" alt="HASHMAP COLLISION HANDLING: LINKED LIST VS RED-BLACK TREE" width="800" height="451"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  7. How HashMap Resizing Works
&lt;/h2&gt;

&lt;p&gt;HashMap does not allocate an unlimited array.&lt;/p&gt;

&lt;p&gt;It grows automatically when the number of entries crosses a threshold.&lt;/p&gt;

&lt;p&gt;Two important concepts:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Initial Capacity&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Default initial capacity:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="mi"&gt;16&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Load Factor&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Default load factor:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="mf"&gt;0.75&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The resize threshold is calculated as:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="n"&gt;threshold&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;capacity&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;loadFactor&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Initial Capacity = 16

Load Factor = 0.75

Threshold = 16 * 0.75

Threshold = 12
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When the number of mappings exceeds the threshold, HashMap resizes its internal array.&lt;/p&gt;

&lt;p&gt;The new capacity is generally doubled:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;16 → 32 → 64 → 128 → 256
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Why does HashMap resize?&lt;/p&gt;

&lt;p&gt;As the number of entries increases, collisions may become more frequent.&lt;/p&gt;

&lt;p&gt;Increasing capacity helps distribute entries across more buckets.&lt;/p&gt;

&lt;h3&gt;
  
  
  What happens during resizing?
&lt;/h3&gt;

&lt;p&gt;During resizing:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;A new, larger bucket array is allocated.&lt;/li&gt;
&lt;li&gt;Existing entries are redistributed into the new array.&lt;/li&gt;
&lt;li&gt;Entries are placed into their appropriate new buckets.&lt;/li&gt;
&lt;li&gt;The new array becomes the internal table.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Java 8 introduced an optimization for redistribution.&lt;/p&gt;

&lt;p&gt;Because capacity doubles, entries from an existing bucket either:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Remain at the same index.&lt;/li&gt;
&lt;li&gt;Move to the index obtained by adding the old capacity.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This avoids recalculating the complete hash for every entry.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fktpwhwksazxaj7iff6zp.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fktpwhwksazxaj7iff6zp.jpg" alt="HASHMAP RESIZING: CAPACITY 16 TO 32" width="800" height="451"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  8. How put() Works Internally
&lt;/h2&gt;

&lt;p&gt;Let's understand the simplified flow of the &lt;code&gt;put()&lt;/code&gt; operation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kt"&gt;Map&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;Integer&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;employees&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;HashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="n"&gt;employees&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;101&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"John"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Internally, the process is approximately:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;put(key, value)
       |
       v
Calculate hash
       |
       v
Calculate bucket index
       |
       v
Is bucket empty?
   /       \
 Yes        No
  |          |
Insert     Check existing nodes
  |          |
  |       Same key?
  |        /    \
  |      Yes     No
  |       |       |
  |   Replace    Continue
  |   value      searching
  |               |
  |          Add new node
  |               |
  +---------------+
          |
          v
   Check resize threshold
          |
          v
       Return
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is a simplified conceptual flow. The actual implementation also handles tree bins, null keys, and other special cases.&lt;/p&gt;




&lt;h2&gt;
  
  
  9. How get() Works Internally
&lt;/h2&gt;

&lt;p&gt;Retrieving a value follows a similar process.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kt"&gt;String&lt;/span&gt; &lt;span class="n"&gt;employee&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;employees&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;101&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;HashMap:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Calculates the key's hash.&lt;/li&gt;
&lt;li&gt;Determines the bucket index.&lt;/li&gt;
&lt;li&gt;Checks the first node.&lt;/li&gt;
&lt;li&gt;Compares hash and key equality.&lt;/li&gt;
&lt;li&gt;Traverses the linked list or searches the tree if necessary.&lt;/li&gt;
&lt;li&gt;Returns the matching value.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If the key does not exist, it returns &lt;code&gt;null&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This explains why HashMap provides approximately O(1) average-time lookup.&lt;/p&gt;




&lt;h2&gt;
  
  
  10. Why Are equals() and hashCode() Important?
&lt;/h2&gt;

&lt;p&gt;One of the most common mistakes developers make is overriding &lt;code&gt;equals()&lt;/code&gt; without overriding &lt;code&gt;hashCode()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Consider:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Employee&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nc"&gt;Employee&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@Override&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;boolean&lt;/span&gt; &lt;span class="nf"&gt;equals&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;Object&lt;/span&gt; &lt;span class="n"&gt;obj&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;obj&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;obj&lt;/span&gt; &lt;span class="k"&gt;instanceof&lt;/span&gt; &lt;span class="nc"&gt;Employee&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="nc"&gt;Employee&lt;/span&gt; &lt;span class="n"&gt;other&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Employee&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;obj&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;other&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now consider:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kt"&gt;Map&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Employee&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;employees&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;HashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="n"&gt;employees&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Employee&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;101&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"John"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;employees&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Employee&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;101&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Without a matching &lt;code&gt;hashCode()&lt;/code&gt; implementation, the lookup may fail.&lt;/p&gt;

&lt;p&gt;Why?&lt;/p&gt;

&lt;p&gt;Because two logically equal objects may produce different identity-based hash codes.&lt;/p&gt;

&lt;p&gt;The contract is:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If two objects are equal according to &lt;code&gt;equals()&lt;/code&gt;, they must have the same hashCode.&lt;/li&gt;
&lt;li&gt;Objects with the same hashCode are not necessarily equal.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Correct implementation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Override&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;hashCode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kt"&gt;Integer&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;hashCode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Real-world lesson:&lt;/strong&gt; Always implement &lt;code&gt;equals()&lt;/code&gt; and &lt;code&gt;hashCode()&lt;/code&gt; together when defining custom key objects.&lt;/p&gt;

&lt;p&gt;Also, avoid modifying fields that participate in &lt;code&gt;equals()&lt;/code&gt; and &lt;code&gt;hashCode()&lt;/code&gt; while an object is being used as a HashMap key. Doing so can make the entry difficult to retrieve.&lt;/p&gt;




&lt;h2&gt;
  
  
  11. Time Complexity of HashMap
&lt;/h2&gt;

&lt;p&gt;Let's look at the typical performance characteristics.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Operation&lt;/th&gt;
&lt;th&gt;Average Case&lt;/th&gt;
&lt;th&gt;Worst Case&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;put()&lt;/td&gt;
&lt;td&gt;O(1)&lt;/td&gt;
&lt;td&gt;O(n)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;get()&lt;/td&gt;
&lt;td&gt;O(1)&lt;/td&gt;
&lt;td&gt;O(n)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;remove()&lt;/td&gt;
&lt;td&gt;O(1)&lt;/td&gt;
&lt;td&gt;O(n)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;containsKey()&lt;/td&gt;
&lt;td&gt;O(1)&lt;/td&gt;
&lt;td&gt;O(n)&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;With tree bins, heavily collided buckets can provide O(log n) lookup behavior under normal balanced-tree conditions.&lt;/p&gt;

&lt;p&gt;However, resizing can require O(n) work.&lt;/p&gt;

&lt;p&gt;These complexities describe the general implementation behavior, not a guarantee that every individual operation always takes constant time.&lt;/p&gt;




&lt;h2&gt;
  
  
  12. HashMap vs ConcurrentHashMap
&lt;/h2&gt;

&lt;p&gt;A common question in backend development is:&lt;/p&gt;

&lt;p&gt;Should we use HashMap or ConcurrentHashMap?&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Feature&lt;/th&gt;
&lt;th&gt;HashMap&lt;/th&gt;
&lt;th&gt;ConcurrentHashMap&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Thread-safe&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Null key&lt;/td&gt;
&lt;td&gt;One allowed&lt;/td&gt;
&lt;td&gt;Not allowed&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Null values&lt;/td&gt;
&lt;td&gt;Allowed&lt;/td&gt;
&lt;td&gt;Not allowed&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Concurrent access&lt;/td&gt;
&lt;td&gt;Requires external synchronization&lt;/td&gt;
&lt;td&gt;Supports concurrent operations&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Performance&lt;/td&gt;
&lt;td&gt;Good for single-threaded access&lt;/td&gt;
&lt;td&gt;Designed for concurrent access&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kt"&gt;Map&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;map&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ConcurrentHashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In a multithreaded application, using HashMap without proper synchronization can lead to incorrect behavior when multiple threads modify it concurrently.&lt;/p&gt;

&lt;p&gt;ConcurrentHashMap provides thread-safe operations and is generally a better choice for shared mutable maps.&lt;/p&gt;

&lt;p&gt;Remember: Thread-safe individual operations do not automatically make multi-step business workflows atomic.&lt;/p&gt;




&lt;h2&gt;
  
  
  13. Real-World Usage in Enterprise Applications
&lt;/h2&gt;

&lt;p&gt;HashMap is not just an interview topic. It plays an important role in enterprise backend development.&lt;/p&gt;

&lt;p&gt;Consider a banking application.&lt;/p&gt;

&lt;p&gt;We may use HashMap for:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Transaction Processing&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kt"&gt;Map&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Transaction&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;transactionCache&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
        &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;HashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Useful for temporary in-memory lookups within a controlled execution context.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Configuration Management&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kt"&gt;Map&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;applicationConfig&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
        &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;HashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Grouping Transactions&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kt"&gt;Map&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Transaction&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;transactionsByAccount&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
        &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;HashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;4. API Response Transformation&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kt"&gt;Map&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;Object&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;HashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"status"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"SUCCESS"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"transactionId"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"TXN1001"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"amount"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;5000&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In production applications, choose the appropriate concurrency model and cache technology based on data size, lifecycle, consistency, and deployment architecture.&lt;/p&gt;

&lt;p&gt;For distributed caching across multiple microservice instances, an in-memory HashMap is not a replacement for Redis or another distributed cache.&lt;/p&gt;




&lt;h2&gt;
  
  
  14. Best Practices for Using HashMap
&lt;/h2&gt;

&lt;p&gt;A few practical recommendations:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Initialize HashMap with a suitable capacity when the approximate number of entries is known.&lt;/li&gt;
&lt;li&gt;Use immutable objects as keys wherever possible.&lt;/li&gt;
&lt;li&gt;Always implement equals() and hashCode() consistently for custom keys.&lt;/li&gt;
&lt;li&gt;Avoid using HashMap for shared mutable state without synchronization.&lt;/li&gt;
&lt;li&gt;Use ConcurrentHashMap for appropriate concurrent access scenarios.&lt;/li&gt;
&lt;li&gt;Do not depend on HashMap iteration order.&lt;/li&gt;
&lt;li&gt;Use LinkedHashMap when insertion order matters.&lt;/li&gt;
&lt;li&gt;Use TreeMap when sorted key ordering is required.&lt;/li&gt;
&lt;li&gt;Avoid unnecessarily large initial capacities because they increase memory consumption.&lt;/li&gt;
&lt;li&gt;Consider distributed caching solutions for cross-instance application caching.&lt;/li&gt;
&lt;/ol&gt;




&lt;h2&gt;
  
  
  15. Key Takeaways
&lt;/h2&gt;

&lt;p&gt;Let's summarize what happens internally:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;HashMap stores entries in an internal array of buckets.&lt;/li&gt;
&lt;li&gt;It uses hashCode() and hash spreading to calculate the hash.&lt;/li&gt;
&lt;li&gt;Bucket indexes are calculated using &lt;code&gt;(n - 1) &amp;amp; hash&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Collisions are handled using linked lists.&lt;/li&gt;
&lt;li&gt;Java 8 introduced Red-Black Tree bins for heavily populated buckets.&lt;/li&gt;
&lt;li&gt;Default initial capacity is 16.&lt;/li&gt;
&lt;li&gt;Default load factor is 0.75.&lt;/li&gt;
&lt;li&gt;Resizing generally doubles the capacity.&lt;/li&gt;
&lt;li&gt;Correct equals() and hashCode() implementations are essential.&lt;/li&gt;
&lt;li&gt;HashMap is not thread-safe.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Understanding these internals helps us write better Java applications, troubleshoot performance issues, and make informed architectural decisions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;A good Java developer knows how to use HashMap. An experienced Java engineer understands what happens behind the scenes.&lt;/strong&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Interview Questions to Test Your Understanding
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Why is HashMap capacity always a power of two?&lt;/li&gt;
&lt;li&gt;Why does HashMap use &lt;code&gt;h ^ (h &amp;gt;&amp;gt;&amp;gt; 16)&lt;/code&gt;?&lt;/li&gt;
&lt;li&gt;What happens when two different keys have the same hashCode?&lt;/li&gt;
&lt;li&gt;What is the difference between collision handling in Java 7 and Java 8?&lt;/li&gt;
&lt;li&gt;Why does HashMap convert a linked list into a Red-Black Tree?&lt;/li&gt;
&lt;li&gt;What are TREEIFY_THRESHOLD and MIN_TREEIFY_CAPACITY?&lt;/li&gt;
&lt;li&gt;What happens when the load factor threshold is exceeded?&lt;/li&gt;
&lt;li&gt;Can two different objects have the same hashCode?&lt;/li&gt;
&lt;li&gt;Why is HashMap not thread-safe?&lt;/li&gt;
&lt;li&gt;What happens if we modify a key after inserting it into a HashMap?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If you can explain these questions with internal implementation details and practical examples, you have a strong understanding of HashMap.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;What's Next?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In the next article, we'll explore another important Java Collections topic:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;HashMap vs LinkedHashMap vs TreeMap: Internal Differences, Performance and Real-World Use Cases.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Follow me for more practical Java, Spring Boot, Microservices, Kafka, System Design and Enterprise Architecture insights.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ram The Architect (RTA)&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>java</category>
      <category>beginners</category>
      <category>programming</category>
      <category>performance</category>
    </item>
    <item>
      <title>Java Concurrency: synchronized vs Lock vs Atomic Classes – Choosing the Right Synchronization Mechanism</title>
      <dc:creator>Ramanjaneyulu Boya</dc:creator>
      <pubDate>Wed, 18 Nov 2026 14:35:08 +0000</pubDate>
      <link>https://dev.to/ramthearchitect/java-concurrency-synchronized-vs-lock-vs-atomic-classes-choosing-the-right-synchronization-3lj7</link>
      <guid>https://dev.to/ramthearchitect/java-concurrency-synchronized-vs-lock-vs-atomic-classes-choosing-the-right-synchronization-3lj7</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ftolgqfhj8dl5st8mwb08.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ftolgqfhj8dl5st8mwb08.jpg" alt="Java concurrency" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Java concurrency is one of the most important topics for building scalable, reliable, and high-performance backend applications.&lt;/p&gt;

&lt;p&gt;In modern enterprise applications, multiple threads frequently access shared resources such as:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Bank account balances&lt;/li&gt;
&lt;li&gt;Payment transaction records&lt;/li&gt;
&lt;li&gt;Order processing states&lt;/li&gt;
&lt;li&gt;Inventory quantities&lt;/li&gt;
&lt;li&gt;Shared in-memory caches&lt;/li&gt;
&lt;li&gt;Transaction counters&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;When multiple threads modify shared data simultaneously, &lt;strong&gt;race conditions, data inconsistency, and unexpected application behavior&lt;/strong&gt; can occur.&lt;/p&gt;

&lt;p&gt;Java provides several synchronization mechanisms to handle these problems.&lt;/p&gt;

&lt;p&gt;Three commonly used approaches are:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;code&gt;synchronized&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Lock&lt;/code&gt; API&lt;/li&gt;
&lt;li&gt;Atomic classes (&lt;code&gt;AtomicInteger&lt;/code&gt;, &lt;code&gt;AtomicLong&lt;/code&gt;, &lt;code&gt;AtomicReference&lt;/code&gt;, etc.)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;But which one should we use?&lt;/p&gt;

&lt;p&gt;Let's understand their internal behavior, differences, practical implementations, and real-world use cases.&lt;/p&gt;




&lt;h2&gt;
  
  
  1. Understanding the Race Condition
&lt;/h2&gt;

&lt;p&gt;Consider a simple bank account application.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;BankAccount&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;balance&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;withdraw&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;balance&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;balance&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;getBalance&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Suppose two threads execute the withdrawal operation simultaneously:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Thread 1 withdraws ₹500.&lt;/li&gt;
&lt;li&gt;Thread 2 withdraws ₹300.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Both threads read the original balance before either completes its update.&lt;/p&gt;

&lt;p&gt;This can produce an incorrect final balance.&lt;/p&gt;

&lt;p&gt;The problem is that the operation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="n"&gt;balance&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;balance&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;is not atomic.&lt;/p&gt;

&lt;p&gt;It involves multiple steps:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Read the current balance.&lt;/li&gt;
&lt;li&gt;Calculate the new balance.&lt;/li&gt;
&lt;li&gt;Write the updated balance.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Without synchronization, concurrent execution can cause a lost update.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Solution:&lt;/strong&gt; Protect shared mutable state using an appropriate concurrency mechanism.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. synchronized – Intrinsic Locking
&lt;/h2&gt;

&lt;p&gt;Java's &lt;code&gt;synchronized&lt;/code&gt; keyword provides built-in mutual exclusion.&lt;/p&gt;

&lt;p&gt;Only one thread can execute a synchronized block protected by the same monitor at a time.&lt;/p&gt;

&lt;h3&gt;
  
  
  Example: Method-Level Synchronization
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;BankAccount&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;balance&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;synchronized&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;withdraw&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;balance&lt;/span&gt; &lt;span class="o"&gt;-=&lt;/span&gt; &lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;synchronized&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;getBalance&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When a thread enters a synchronized instance method, it acquires the object's intrinsic monitor lock.&lt;/p&gt;

&lt;p&gt;Other threads attempting to enter synchronized methods or blocks protected by that same monitor must wait.&lt;/p&gt;

&lt;h3&gt;
  
  
  Block-Level Synchronization
&lt;/h3&gt;

&lt;p&gt;Instead of synchronizing an entire method, we can synchronize only the critical section.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;withdraw&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="k"&gt;synchronized&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;balance&lt;/span&gt; &lt;span class="o"&gt;-=&lt;/span&gt; &lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This can reduce unnecessary lock contention when other parts of the method do not need protection.&lt;/p&gt;

&lt;h3&gt;
  
  
  Static Synchronization
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="k"&gt;synchronized&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;process&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// Thread-safe static operation&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A static synchronized method acquires the monitor associated with the class's &lt;code&gt;Class&lt;/code&gt; object rather than an individual instance.&lt;/p&gt;

&lt;h3&gt;
  
  
  How synchronized Works Internally
&lt;/h3&gt;

&lt;p&gt;At the JVM level, synchronized operations use monitor-related mechanisms.&lt;/p&gt;

&lt;p&gt;The JVM manages monitor acquisition and release. When a thread exits a synchronized block, normally or exceptionally, the monitor is released automatically.&lt;/p&gt;

&lt;p&gt;Modern JVM implementations also optimize synchronization using techniques such as lock elimination and lock coarsening where applicable.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Important:&lt;/strong&gt; Synchronization also establishes a happens-before relationship. Changes made by one thread before releasing a monitor become visible to another thread after it subsequently acquires the same monitor.&lt;/p&gt;

&lt;h3&gt;
  
  
  When to Use synchronized?
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Simple critical sections.&lt;/li&gt;
&lt;li&gt;Protecting shared mutable objects.&lt;/li&gt;
&lt;li&gt;Maintaining consistency across multiple related fields.&lt;/li&gt;
&lt;li&gt;When explicit lock management is unnecessary.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  3. Lock API – Explicit Locking
&lt;/h2&gt;

&lt;p&gt;Java provides the &lt;code&gt;java.util.concurrent.locks&lt;/code&gt; package for more flexible synchronization.&lt;/p&gt;

&lt;p&gt;The most commonly used implementation is &lt;code&gt;ReentrantLock&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Unlike synchronized, the Lock API provides additional capabilities:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Explicit lock acquisition and release.&lt;/li&gt;
&lt;li&gt;Non-blocking lock acquisition using &lt;code&gt;tryLock()&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Interruptible lock acquisition.&lt;/li&gt;
&lt;li&gt;Optional fairness policy.&lt;/li&gt;
&lt;li&gt;Multiple condition variables using &lt;code&gt;Condition&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Example: ReentrantLock
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;java&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;util&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;concurrent&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;locks&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;ReentrantLock&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;BankAccount&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;balance&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;ReentrantLock&lt;/span&gt; &lt;span class="k"&gt;lock&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
            &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ReentrantLock&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;withdraw&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

        &lt;span class="k"&gt;lock&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;lock&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="n"&gt;balance&lt;/span&gt; &lt;span class="o"&gt;-=&lt;/span&gt; &lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;finally&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;lock&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;unlock&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;getBalance&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

        &lt;span class="k"&gt;lock&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;lock&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;finally&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;lock&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;unlock&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Why finally Is Important
&lt;/h3&gt;

&lt;p&gt;Consider this scenario:&lt;/p&gt;

&lt;p&gt;A thread acquires a lock and an exception occurs during business processing.&lt;/p&gt;

&lt;p&gt;If the lock is not released, other threads may remain blocked indefinitely.&lt;/p&gt;

&lt;p&gt;That's why we should always release explicitly acquired locks inside a &lt;code&gt;finally&lt;/code&gt; block.&lt;/p&gt;

&lt;h3&gt;
  
  
  tryLock() – Avoid Waiting Indefinitely
&lt;/h3&gt;

&lt;p&gt;One important advantage of ReentrantLock is &lt;code&gt;tryLock()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;It allows a thread to attempt acquiring a lock without waiting indefinitely.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;processPayment&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;lock&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;tryLock&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

        &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
                &lt;span class="s2"&gt;"Processing payment..."&lt;/span&gt;
            &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;finally&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;lock&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;unlock&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="s2"&gt;"Resource is currently busy"&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can also use a timed lock attempt:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;lock&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;tryLock&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;TimeUnit&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;SECONDS&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// Business logic&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;finally&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;lock&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;unlock&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This can be useful when an application needs to avoid waiting indefinitely for a contended resource.&lt;/p&gt;

&lt;h3&gt;
  
  
  Fairness in ReentrantLock
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;ReentrantLock&lt;/span&gt; &lt;span class="k"&gt;lock&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
        &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ReentrantLock&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;true&lt;/code&gt; parameter enables a fairness policy.&lt;/p&gt;

&lt;p&gt;A fair lock generally favors the longest-waiting thread when granting access.&lt;/p&gt;

&lt;p&gt;However, fairness can reduce throughput and does not guarantee fair scheduling of application threads.&lt;/p&gt;

&lt;h3&gt;
  
  
  Condition – Advanced Thread Coordination
&lt;/h3&gt;

&lt;p&gt;The Lock API also supports Condition objects.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;ReentrantLock&lt;/span&gt; &lt;span class="k"&gt;lock&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
        &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ReentrantLock&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;Condition&lt;/span&gt; &lt;span class="n"&gt;condition&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
        &lt;span class="k"&gt;lock&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;newCondition&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Threads can wait for a condition using:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="n"&gt;condition&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;await&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Another thread can signal waiting threads using:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="n"&gt;condition&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;signal&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is useful in producer-consumer implementations and other coordination scenarios.&lt;/p&gt;

&lt;p&gt;As with &lt;code&gt;Object.wait()&lt;/code&gt;, condition waits should generally be used inside a loop that checks the required condition.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. Atomic Classes – Lock-Free Operations
&lt;/h2&gt;

&lt;p&gt;Java provides atomic classes in the &lt;code&gt;java.util.concurrent.atomic&lt;/code&gt; package.&lt;/p&gt;

&lt;p&gt;Examples include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;AtomicInteger&lt;/li&gt;
&lt;li&gt;AtomicLong&lt;/li&gt;
&lt;li&gt;AtomicBoolean&lt;/li&gt;
&lt;li&gt;AtomicReference&lt;/li&gt;
&lt;li&gt;LongAdder&lt;/li&gt;
&lt;li&gt;LongAccumulator&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;These classes support thread-safe operations using atomic updates.&lt;/p&gt;

&lt;p&gt;Many atomic operations use Compare-And-Set (CAS) mechanisms.&lt;/p&gt;

&lt;h3&gt;
  
  
  What Is CAS?
&lt;/h3&gt;

&lt;p&gt;CAS stands for Compare-And-Set.&lt;/p&gt;

&lt;p&gt;It works conceptually as follows:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Read the current value.&lt;/li&gt;
&lt;li&gt;Compare it with the expected value.&lt;/li&gt;
&lt;li&gt;If both match, update it with the new value.&lt;/li&gt;
&lt;li&gt;If another thread changed the value, retry or report failure.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The operation succeeds only if the expected value is still current.&lt;/p&gt;

&lt;h3&gt;
  
  
  Example: AtomicInteger
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;java&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;util&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;concurrent&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;atomic&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;AtomicInteger&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;TransactionCounter&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;AtomicInteger&lt;/span&gt; &lt;span class="n"&gt;counter&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
            &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;AtomicInteger&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;increment&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;counter&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;incrementAndGet&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;getCount&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;counter&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Multiple threads can safely increment the counter without explicitly using synchronized or ReentrantLock.&lt;/p&gt;

&lt;h3&gt;
  
  
  CAS Example
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;AtomicInteger&lt;/span&gt; &lt;span class="n"&gt;balance&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
        &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;AtomicInteger&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kt"&gt;boolean&lt;/span&gt; &lt;span class="n"&gt;updated&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
        &lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;compareAndSet&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;100&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If another thread changes the balance between reading and updating, the CAS operation fails.&lt;/p&gt;

&lt;p&gt;The application can retry with the latest value if appropriate.&lt;/p&gt;

&lt;h3&gt;
  
  
  AtomicReference
&lt;/h3&gt;

&lt;p&gt;AtomicReference is useful when we need atomic updates of object references.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;java&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;util&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;concurrent&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;atomic&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;AtomicReference&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;PaymentStatus&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;AtomicReference&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;status&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
            &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;AtomicReference&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"PENDING"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;boolean&lt;/span&gt; &lt;span class="nf"&gt;completePayment&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;compareAndSet&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="s2"&gt;"PENDING"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s2"&gt;"COMPLETED"&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This ensures that only one thread can successfully transition the status from PENDING to COMPLETED using this operation.&lt;/p&gt;

&lt;h3&gt;
  
  
  What About LongAdder?
&lt;/h3&gt;

&lt;p&gt;For highly concurrent counters, LongAdder can provide better throughput than AtomicLong because it distributes updates across multiple internal cells.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;java&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;util&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;concurrent&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;atomic&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;LongAdder&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;RequestMetrics&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;LongAdder&lt;/span&gt; &lt;span class="n"&gt;requestCount&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
            &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;LongAdder&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;recordRequest&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;requestCount&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;increment&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="nf"&gt;getRequestCount&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;requestCount&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;LongAdder is particularly useful for metrics and statistics where highly contended increments are common.&lt;/p&gt;

&lt;p&gt;However, its &lt;code&gt;sum()&lt;/code&gt; method is not an atomic snapshot during concurrent updates.&lt;/p&gt;

&lt;p&gt;It should not be used where every read must represent a strictly consistent transactional value.&lt;/p&gt;

&lt;h2&gt;
  
  
  5. synchronized vs Lock vs Atomic – Key Differences
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Feature&lt;/th&gt;
&lt;th&gt;synchronized&lt;/th&gt;
&lt;th&gt;ReentrantLock&lt;/th&gt;
&lt;th&gt;Atomic Classes&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Lock mechanism&lt;/td&gt;
&lt;td&gt;Intrinsic monitor&lt;/td&gt;
&lt;td&gt;Explicit lock&lt;/td&gt;
&lt;td&gt;CAS / atomic operations&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Lock release&lt;/td&gt;
&lt;td&gt;Automatic&lt;/td&gt;
&lt;td&gt;Manual&lt;/td&gt;
&lt;td&gt;Not applicable for ordinary atomic operations&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;tryLock()&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;CAS operations can fail immediately&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Interruptible acquisition&lt;/td&gt;
&lt;td&gt;No direct equivalent&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;Depends on operation&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Fairness option&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Multiple conditions&lt;/td&gt;
&lt;td&gt;wait/notify&lt;/td&gt;
&lt;td&gt;Condition&lt;/td&gt;
&lt;td&gt;Not built in&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Multiple-field protection&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;Requires additional coordination&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Best suited for&lt;/td&gt;
&lt;td&gt;Critical sections&lt;/td&gt;
&lt;td&gt;Complex locking&lt;/td&gt;
&lt;td&gt;Independent atomic state updates&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h2&gt;
  
  
  6. Real-World Banking Application Use Cases
&lt;/h2&gt;

&lt;p&gt;Let's understand where these mechanisms fit in an enterprise banking application.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Scenario 1: Updating Customer Account Details&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A customer account contains multiple related fields:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Account balance&lt;/li&gt;
&lt;li&gt;Account status&lt;/li&gt;
&lt;li&gt;Transaction limits&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;When multiple fields must be updated consistently under one shared in-memory synchronization boundary, synchronized or Lock can be appropriate.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Scenario 2: Transaction Request Counter&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A payment service tracks the number of incoming requests.&lt;/p&gt;

&lt;p&gt;Using AtomicLong or LongAdder is a good approach depending on whether exact atomic reads or high-throughput metrics are required.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Scenario 3: Payment Status Transition&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A payment moves through different states:&lt;/p&gt;

&lt;p&gt;PENDING → PROCESSING → COMPLETED&lt;/p&gt;

&lt;p&gt;AtomicReference with compareAndSet() can prevent multiple threads from successfully applying the same state transition.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Scenario 4: Resource Coordination&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A service manages a shared in-memory resource that requires timed lock acquisition and interruption support.&lt;/p&gt;

&lt;p&gt;ReentrantLock provides more flexibility than synchronized.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Important architectural consideration:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Java synchronization only coordinates threads sharing the same JVM-level synchronization object.&lt;/p&gt;

&lt;p&gt;In distributed microservices, multiple application instances may process the same payment simultaneously.&lt;/p&gt;

&lt;p&gt;For distributed consistency, we need additional mechanisms such as:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Database transactions.&lt;/li&gt;
&lt;li&gt;Optimistic locking with version columns.&lt;/li&gt;
&lt;li&gt;Pessimistic database locking.&lt;/li&gt;
&lt;li&gt;Unique constraints and idempotency keys.&lt;/li&gt;
&lt;li&gt;Distributed coordination where justified.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Never assume that synchronized or AtomicInteger can guarantee consistency across multiple service instances.&lt;/p&gt;

&lt;h2&gt;
  
  
  7. Performance Considerations
&lt;/h2&gt;

&lt;p&gt;There is no universal winner among synchronized, Lock, and Atomic classes.&lt;/p&gt;

&lt;p&gt;Performance depends on:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Number of concurrent threads.&lt;/li&gt;
&lt;li&gt;Lock contention.&lt;/li&gt;
&lt;li&gt;Duration of critical sections.&lt;/li&gt;
&lt;li&gt;Frequency of updates.&lt;/li&gt;
&lt;li&gt;CPU architecture.&lt;/li&gt;
&lt;li&gt;JVM optimizations.&lt;/li&gt;
&lt;li&gt;Application workload.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A few practical guidelines:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Prefer synchronized for straightforward mutual exclusion.&lt;/li&gt;
&lt;li&gt;Use ReentrantLock when you need timed acquisition, interruptibility, fairness, or multiple conditions.&lt;/li&gt;
&lt;li&gt;Use atomic classes for independent state updates.&lt;/li&gt;
&lt;li&gt;Consider LongAdder for highly contended metrics counters.&lt;/li&gt;
&lt;li&gt;Avoid unnecessarily large synchronized blocks.&lt;/li&gt;
&lt;li&gt;Never hold locks while performing slow network or database operations unless absolutely necessary.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;For performance-sensitive systems, validate assumptions using JMH rather than relying on theoretical comparisons.&lt;/p&gt;

&lt;h2&gt;
  
  
  8. Interview Questions – Frequently Asked
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Q1. What is the main difference between synchronized and ReentrantLock?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;synchronized provides intrinsic locking with automatic release. ReentrantLock provides explicit locking with advanced features such as tryLock(), interruptible acquisition, and configurable fairness.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Q2. Is synchronized reentrant?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Yes. The same thread can acquire the same intrinsic monitor multiple times.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Q3. What is CAS?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Compare-And-Set is an atomic operation that updates a value only if it matches an expected value.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Q4. Are AtomicInteger operations thread-safe?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Yes. Its atomic methods provide thread-safe updates to the integer value.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Q5. Can AtomicInteger replace synchronized completely?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;No. AtomicInteger is suitable for individual atomic state operations. It does not automatically protect complex operations involving multiple fields or multiple independent objects.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Q6. What happens if unlock() is not called?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The lock remains held, potentially preventing other threads from acquiring it. Always use try-finally.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Q7. What is the difference between AtomicLong and LongAdder?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;AtomicLong provides atomic updates and reads of one value. LongAdder distributes updates across cells to reduce contention, making it useful for high-throughput statistics.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Q8. Does synchronized guarantee thread execution order?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;No. It guarantees mutual exclusion and memory visibility through monitor synchronization, but does not guarantee the order in which threads acquire the monitor.&lt;/p&gt;




&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Choosing the right synchronization mechanism is essential for building reliable concurrent Java applications.&lt;/p&gt;

&lt;p&gt;Remember these practical guidelines:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;synchronized:&lt;/strong&gt; Simple and effective mutual exclusion.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;ReentrantLock:&lt;/strong&gt; Advanced locking and thread coordination.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Atomic Classes:&lt;/strong&gt; Efficient atomic updates for independent shared state.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;LongAdder:&lt;/strong&gt; High-throughput counters and metrics.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;As Java developers working on enterprise applications, understanding these mechanisms is more important than simply knowing their syntax.&lt;/p&gt;

&lt;p&gt;The real skill is identifying the concurrency problem and selecting the simplest mechanism that guarantees correctness without introducing unnecessary complexity.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Write thread-safe code. Design for concurrency. Build reliable systems.&lt;/strong&gt;&lt;/p&gt;




&lt;h3&gt;
  
  
  About the Author
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Ramu Boya | Ram The Architect (RTA)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Java Backend | Spring Boot | Microservices | System Design | Cloud Architecture | GenAI&lt;/p&gt;

&lt;p&gt;Sharing practical insights on enterprise Java engineering, distributed systems, fintech architecture, and modern application development.&lt;/p&gt;

</description>
      <category>java</category>
      <category>backend</category>
      <category>programming</category>
      <category>multithreading</category>
    </item>
    <item>
      <title>Java Virtual Threads: Solving the Thread-per-Request Problem</title>
      <dc:creator>Ramanjaneyulu Boya</dc:creator>
      <pubDate>Tue, 17 Nov 2026 16:55:51 +0000</pubDate>
      <link>https://dev.to/ramthearchitect/java-virtual-threads-solving-the-thread-per-request-problem-19nh</link>
      <guid>https://dev.to/ramthearchitect/java-virtual-threads-solving-the-thread-per-request-problem-19nh</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;For years, Java developers have relied on the traditional thread-per-request model to build scalable backend applications.&lt;/p&gt;

&lt;p&gt;Every incoming HTTP request gets assigned a thread. That thread handles the request, executes business logic, communicates with databases, calls downstream services, and finally sends the response.&lt;/p&gt;

&lt;p&gt;This model works well for many applications.&lt;/p&gt;

&lt;p&gt;But what happens when your application receives thousands of concurrent requests?&lt;/p&gt;

&lt;p&gt;Traditional platform threads are relatively expensive resources. Creating and managing thousands of threads consumes memory, increases context switching, and can eventually limit application scalability.&lt;/p&gt;

&lt;p&gt;This is where &lt;strong&gt;Java Virtual Threads&lt;/strong&gt;, introduced as a preview feature in Java 19 and finalized in Java 21 (JEP 444), change the game.&lt;/p&gt;

&lt;p&gt;Virtual Threads allow Java applications to handle large numbers of concurrent tasks with significantly lower thread-management overhead.&lt;/p&gt;

&lt;p&gt;Let's understand how they work and why they matter for modern microservices.&lt;/p&gt;




&lt;h2&gt;
  
  
  1. The Problem with Traditional Platform Threads
&lt;/h2&gt;

&lt;p&gt;Traditionally, Java applications use platform threads.&lt;/p&gt;

&lt;p&gt;A platform thread is backed by an operating-system thread.&lt;/p&gt;

&lt;p&gt;Consider a Spring Boot REST API handling customer account requests.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@RestController&lt;/span&gt;
&lt;span class="nd"&gt;@RequestMapping&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"/accounts"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;AccountController&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="nd"&gt;@GetMapping&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"/{id}"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;Account&lt;/span&gt; &lt;span class="nf"&gt;getAccount&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nd"&gt;@PathVariable&lt;/span&gt; &lt;span class="kt"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;accountService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getAccount&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Under a traditional thread-per-request model:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;A request arrives.&lt;/li&gt;
&lt;li&gt;The server assigns a platform thread.&lt;/li&gt;
&lt;li&gt;The thread executes business logic.&lt;/li&gt;
&lt;li&gt;It queries the database.&lt;/li&gt;
&lt;li&gt;It waits for the database response.&lt;/li&gt;
&lt;li&gt;It returns the response.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The biggest problem is that the thread may spend most of its time waiting for I/O operations.&lt;/p&gt;

&lt;p&gt;For example:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Database queries&lt;/li&gt;
&lt;li&gt;REST API calls&lt;/li&gt;
&lt;li&gt;Kafka-related blocking operations&lt;/li&gt;
&lt;li&gt;External payment gateway calls&lt;/li&gt;
&lt;li&gt;File operations&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;While waiting, the platform thread remains occupied.&lt;/p&gt;

&lt;h3&gt;
  
  
  What happens under high concurrency?
&lt;/h3&gt;

&lt;p&gt;Imagine:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;10,000 concurrent HTTP requests.&lt;/li&gt;
&lt;li&gt;Each request takes 500 ms.&lt;/li&gt;
&lt;li&gt;400 ms is spent waiting for external I/O.&lt;/li&gt;
&lt;li&gt;100 ms is spent executing business logic.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A large number of platform threads may remain occupied while waiting for I/O.&lt;/p&gt;

&lt;p&gt;Increasing the thread pool size is not an unlimited solution.&lt;/p&gt;

&lt;p&gt;It introduces additional overhead:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Higher memory consumption.&lt;/li&gt;
&lt;li&gt;More operating-system thread scheduling.&lt;/li&gt;
&lt;li&gt;Increased context switching.&lt;/li&gt;
&lt;li&gt;Thread pool saturation.&lt;/li&gt;
&lt;li&gt;Reduced application throughput under heavy load.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The real challenge is not necessarily CPU processing.&lt;/p&gt;

&lt;p&gt;It is managing concurrency efficiently when requests spend significant time waiting.&lt;/p&gt;




&lt;h2&gt;
  
  
  2. What Are Java Virtual Threads?
&lt;/h2&gt;

&lt;p&gt;Virtual Threads are lightweight threads managed by the JVM rather than being directly mapped one-to-one to operating-system threads.&lt;/p&gt;

&lt;p&gt;They were finalized in Java 21 through JEP 444.&lt;/p&gt;

&lt;p&gt;Unlike platform threads, millions of virtual threads can potentially be created without requiring millions of operating-system threads.&lt;/p&gt;

&lt;p&gt;The JVM schedules virtual threads onto a smaller number of platform threads called &lt;strong&gt;carrier threads&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Think of it this way:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Virtual Thread: Represents an application task.&lt;/li&gt;
&lt;li&gt;Carrier Thread: Platform thread that executes a virtual thread.&lt;/li&gt;
&lt;li&gt;JVM Scheduler: Coordinates scheduling of virtual threads.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;When a virtual thread performs a supported blocking operation, it can be suspended, allowing its carrier thread to execute another virtual thread.&lt;/p&gt;

&lt;p&gt;When the operation completes, the suspended virtual thread becomes eligible to resume.&lt;/p&gt;

&lt;p&gt;This makes blocking-style code much more scalable for I/O-intensive workloads.&lt;/p&gt;




&lt;h2&gt;
  
  
  3. Platform Threads vs Virtual Threads
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Feature&lt;/th&gt;
&lt;th&gt;Platform Threads&lt;/th&gt;
&lt;th&gt;Virtual Threads&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Managed by&lt;/td&gt;
&lt;td&gt;OS/JVM&lt;/td&gt;
&lt;td&gt;JVM&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;OS thread mapping&lt;/td&gt;
&lt;td&gt;Typically 1:1&lt;/td&gt;
&lt;td&gt;M:N scheduling&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Creation cost&lt;/td&gt;
&lt;td&gt;Relatively high&lt;/td&gt;
&lt;td&gt;Very low&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Memory overhead&lt;/td&gt;
&lt;td&gt;Higher&lt;/td&gt;
&lt;td&gt;Much lower&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Large concurrency&lt;/td&gt;
&lt;td&gt;Resource-intensive&lt;/td&gt;
&lt;td&gt;More efficient&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Best suited for&lt;/td&gt;
&lt;td&gt;CPU-intensive tasks&lt;/td&gt;
&lt;td&gt;I/O-intensive tasks&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Programming model&lt;/td&gt;
&lt;td&gt;Blocking or asynchronous&lt;/td&gt;
&lt;td&gt;Blocking-style code&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Important:&lt;/strong&gt; Virtual Threads do not make CPU-intensive operations faster. They primarily improve scalability when many tasks spend time waiting.&lt;/p&gt;




&lt;h2&gt;
  
  
  4. Creating Virtual Threads in Java 21
&lt;/h2&gt;

&lt;p&gt;Java 21 provides simple APIs for creating virtual threads.&lt;/p&gt;

&lt;h3&gt;
  
  
  Approach 1: Thread.ofVirtual()
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;VirtualThreadExample&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;throws&lt;/span&gt; &lt;span class="nc"&gt;Exception&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

        &lt;span class="nc"&gt;Thread&lt;/span&gt; &lt;span class="n"&gt;thread&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Thread&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;ofVirtual&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;start&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
                &lt;span class="s2"&gt;"Running on: "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt;
                &lt;span class="nc"&gt;Thread&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;currentThread&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="n"&gt;thread&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Approach 2: Thread.startVirtualThread()
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;VirtualThreadExample&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

        &lt;span class="nc"&gt;Thread&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;startVirtualThread&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

            &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
                &lt;span class="s2"&gt;"Hello from Virtual Thread"&lt;/span&gt;
            &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Approach 3: Virtual Thread Executor
&lt;/h3&gt;

&lt;p&gt;For application-level task execution, Java provides a dedicated executor.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;java&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;util&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;concurrent&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;VirtualThreadExecutorExample&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;throws&lt;/span&gt; &lt;span class="nc"&gt;Exception&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

        &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ExecutorService&lt;/span&gt; &lt;span class="n"&gt;executor&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
                 &lt;span class="nc"&gt;Executors&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;newVirtualThreadPerTaskExecutor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

            &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

                &lt;span class="n"&gt;executor&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;submit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

                    &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
                        &lt;span class="nc"&gt;Thread&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;currentThread&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                    &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

                &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each submitted task gets its own virtual thread.&lt;/p&gt;

&lt;p&gt;Unlike a fixed-size thread pool, this executor is designed around creating a new virtual thread per task.&lt;/p&gt;




&lt;h2&gt;
  
  
  5. How Virtual Threads Work Internally
&lt;/h2&gt;

&lt;p&gt;Understanding the internal architecture is important for experienced Java developers.&lt;/p&gt;

&lt;p&gt;Virtual Threads use a scheduling mechanism involving carrier threads.&lt;/p&gt;

&lt;p&gt;Consider this execution flow:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;A virtual thread is created.&lt;/li&gt;
&lt;li&gt;The JVM schedules it onto a carrier platform thread.&lt;/li&gt;
&lt;li&gt;The virtual thread starts executing application code.&lt;/li&gt;
&lt;li&gt;It reaches a supported blocking I/O operation.&lt;/li&gt;
&lt;li&gt;The virtual thread is suspended.&lt;/li&gt;
&lt;li&gt;The carrier thread becomes available for another virtual thread.&lt;/li&gt;
&lt;li&gt;Once the I/O operation completes, the virtual thread becomes runnable again.&lt;/li&gt;
&lt;li&gt;The scheduler assigns it to a carrier thread to continue execution.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This process is called &lt;strong&gt;unmounting and mounting&lt;/strong&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Mounting: A virtual thread runs on a carrier thread.&lt;/li&gt;
&lt;li&gt;Unmounting: A virtual thread temporarily releases its carrier thread.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is one of the fundamental mechanisms that makes virtual threads efficient.&lt;/p&gt;

&lt;h3&gt;
  
  
  Important internal concepts
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Carrier Threads&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;These are ordinary platform threads that execute virtual threads.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Continuation&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A continuation represents the execution state of a virtual thread, allowing it to suspend and resume.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ForkJoinPool Scheduler&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The default virtual thread scheduler uses a ForkJoinPool implementation to schedule virtual threads onto carrier threads.&lt;/p&gt;




&lt;h2&gt;
  
  
  6. Using Virtual Threads in Spring Boot 3.2+
&lt;/h2&gt;

&lt;p&gt;Spring Boot 3.2 introduced built-in support for virtual threads.&lt;/p&gt;

&lt;p&gt;With Java 21 and Spring Boot 3.2+, enabling virtual threads is straightforward.&lt;/p&gt;

&lt;p&gt;Add the following configuration to application.properties:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight properties"&gt;&lt;code&gt;&lt;span class="na"&gt;spring.threads.virtual.enabled&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That's it!&lt;/p&gt;

&lt;p&gt;Spring Boot can configure supported task execution and scheduling infrastructure to use virtual threads.&lt;/p&gt;

&lt;p&gt;For Spring MVC applications using embedded Tomcat or Jetty, supported request-processing infrastructure can also use virtual threads.&lt;/p&gt;

&lt;h3&gt;
  
  
  Example: Spring Boot REST Controller
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@RestController&lt;/span&gt;
&lt;span class="nd"&gt;@RequestMapping&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"/payments"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;PaymentController&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;PaymentService&lt;/span&gt; &lt;span class="n"&gt;paymentService&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;PaymentController&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;PaymentService&lt;/span&gt; &lt;span class="n"&gt;paymentService&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;paymentService&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;paymentService&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@PostMapping&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;ResponseEntity&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;processPayment&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="nd"&gt;@RequestBody&lt;/span&gt; &lt;span class="nc"&gt;PaymentRequest&lt;/span&gt; &lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

        &lt;span class="n"&gt;paymentService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;processPayment&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;ResponseEntity&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;ok&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="s2"&gt;"Payment processed successfully"&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The controller can continue using a familiar synchronous programming model.&lt;/p&gt;

&lt;p&gt;Virtual threads help the application manage concurrent blocking requests more efficiently.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; Enabling virtual threads does not automatically make every component of an application virtual-thread-aware. Verify the behavior of your server, task executors, libraries, and integrations.&lt;/p&gt;




&lt;h2&gt;
  
  
  7. Real-World Fintech Example: Payment Processing
&lt;/h2&gt;

&lt;p&gt;Consider a banking application processing payment requests.&lt;/p&gt;

&lt;p&gt;A single payment request may involve:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Customer authentication.&lt;/li&gt;
&lt;li&gt;Account balance validation.&lt;/li&gt;
&lt;li&gt;Fraud detection service invocation.&lt;/li&gt;
&lt;li&gt;Database transaction.&lt;/li&gt;
&lt;li&gt;External payment gateway integration.&lt;/li&gt;
&lt;li&gt;Transaction status update.&lt;/li&gt;
&lt;li&gt;Response generation.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Several operations involve waiting for external systems.&lt;/p&gt;

&lt;h3&gt;
  
  
  Traditional platform thread model
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Incoming Payment Request
          |
          v
   Platform Thread
          |
          v
   Account Validation
          |
          v
   Fraud Detection API
          |
          v
   Database Operation
          |
          v
   Payment Gateway
          |
          v
   Response
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;During blocking operations, the platform thread may remain occupied.&lt;/p&gt;

&lt;h3&gt;
  
  
  Virtual thread model
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Incoming Payment Request
          |
          v
    Virtual Thread
          |
          v
   Account Validation
          |
          v
   Fraud Detection API
          |
          | Waiting
          v
   Virtual Thread Suspended
          |
     Carrier Released
          |
          v
   I/O Operation Completes
          |
          v
   Virtual Thread Resumes
          |
          v
   Database + Payment Gateway
          |
          v
       Response
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The application can support more concurrent requests without requiring a corresponding number of platform threads.&lt;/p&gt;

&lt;p&gt;However, database connection pools, payment gateway rate limits, and downstream service capacity still impose limits.&lt;/p&gt;

&lt;p&gt;Virtual Threads improve concurrency management, not the capacity of external dependencies.&lt;/p&gt;




&lt;h2&gt;
  
  
  8. Virtual Threads vs CompletableFuture vs Reactive Programming
&lt;/h2&gt;

&lt;p&gt;This is a common interview discussion.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Feature&lt;/th&gt;
&lt;th&gt;Virtual Threads&lt;/th&gt;
&lt;th&gt;CompletableFuture&lt;/th&gt;
&lt;th&gt;Reactive Programming&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Programming style&lt;/td&gt;
&lt;td&gt;Synchronous&lt;/td&gt;
&lt;td&gt;Asynchronous&lt;/td&gt;
&lt;td&gt;Non-blocking reactive&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Code readability&lt;/td&gt;
&lt;td&gt;Simple&lt;/td&gt;
&lt;td&gt;Can become complex&lt;/td&gt;
&lt;td&gt;Requires reactive concepts&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Blocking operations&lt;/td&gt;
&lt;td&gt;Supported&lt;/td&gt;
&lt;td&gt;Depends on execution strategy&lt;/td&gt;
&lt;td&gt;Generally avoided&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Thread management&lt;/td&gt;
&lt;td&gt;JVM-managed&lt;/td&gt;
&lt;td&gt;Executor-managed&lt;/td&gt;
&lt;td&gt;Event-loop based&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Best use case&lt;/td&gt;
&lt;td&gt;Blocking I/O workloads&lt;/td&gt;
&lt;td&gt;Async task composition&lt;/td&gt;
&lt;td&gt;End-to-end non-blocking systems&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h3&gt;
  
  
  When should you choose Virtual Threads?
&lt;/h3&gt;

&lt;p&gt;Choose virtual threads when:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Your application uses blocking JDBC.&lt;/li&gt;
&lt;li&gt;You have many synchronous REST API calls.&lt;/li&gt;
&lt;li&gt;Your existing codebase uses imperative Spring MVC.&lt;/li&gt;
&lt;li&gt;You want to improve concurrency without rewriting everything into reactive programming.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  When should you consider Reactive Programming?
&lt;/h3&gt;

&lt;p&gt;Consider reactive programming when:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;You need end-to-end non-blocking I/O.&lt;/li&gt;
&lt;li&gt;You are using reactive database drivers.&lt;/li&gt;
&lt;li&gt;You have complex streaming pipelines.&lt;/li&gt;
&lt;li&gt;Backpressure is an important requirement.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Virtual Threads and Reactive Programming solve related but different problems.&lt;/p&gt;

&lt;p&gt;They are not direct replacements for every other concurrency model.&lt;/p&gt;




&lt;h2&gt;
  
  
  9. Important Limitations and Best Practices
&lt;/h2&gt;

&lt;p&gt;Virtual Threads are powerful, but they are not a magic solution.&lt;/p&gt;

&lt;h3&gt;
  
  
  1. CPU-intensive workloads
&lt;/h3&gt;

&lt;p&gt;Virtual Threads do not increase CPU capacity.&lt;/p&gt;

&lt;p&gt;If your application performs heavy encryption, image processing, or complex calculations, CPU cores remain the primary limitation.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. Database Connection Pool Limits
&lt;/h3&gt;

&lt;p&gt;Suppose your application creates 10,000 virtual threads but has only 50 database connections.&lt;/p&gt;

&lt;p&gt;Only 50 operations can actively use those connections at a time.&lt;/p&gt;

&lt;p&gt;The remaining operations may wait for connection availability.&lt;/p&gt;

&lt;p&gt;Tune database connection pools according to database capacity and workload.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. Avoid Thread Pooling Virtual Threads
&lt;/h3&gt;

&lt;p&gt;Virtual Threads are designed to be created per task.&lt;/p&gt;

&lt;p&gt;Avoid treating them like scarce platform threads that need to be reused in a fixed-size pool.&lt;/p&gt;

&lt;h3&gt;
  
  
  4. Avoid Excessive ThreadLocal Usage
&lt;/h3&gt;

&lt;p&gt;Virtual Threads support ThreadLocal variables, but creating millions of virtual threads with large ThreadLocal values can increase memory consumption.&lt;/p&gt;

&lt;p&gt;Review existing ThreadLocal usage before migration.&lt;/p&gt;

&lt;h3&gt;
  
  
  5. Understand Pinning
&lt;/h3&gt;

&lt;p&gt;Pinning happens when a virtual thread cannot unmount from its carrier thread during certain operations.&lt;/p&gt;

&lt;p&gt;In Java 21, synchronized blocks and methods can cause pinning when a virtual thread blocks while holding a monitor.&lt;/p&gt;

&lt;p&gt;Native or foreign function calls can also pin virtual threads.&lt;/p&gt;

&lt;p&gt;Review long-running blocking operations inside synchronized sections.&lt;/p&gt;

&lt;p&gt;Do not blindly replace every synchronized block with another synchronization mechanism.&lt;/p&gt;

&lt;h3&gt;
  
  
  6. Virtual Threads Do Not Replace Rate Limiting
&lt;/h3&gt;

&lt;p&gt;If a downstream payment gateway supports only 500 concurrent requests, creating 10,000 virtual threads will not increase its capacity.&lt;/p&gt;

&lt;p&gt;Use:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Rate limiting.&lt;/li&gt;
&lt;li&gt;Bulkheads.&lt;/li&gt;
&lt;li&gt;Timeouts.&lt;/li&gt;
&lt;li&gt;Connection pooling.&lt;/li&gt;
&lt;li&gt;Circuit breakers.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Concurrency management must still respect downstream system limits.&lt;/p&gt;




&lt;h2&gt;
  
  
  10. Monitoring Virtual Threads in Production
&lt;/h2&gt;

&lt;p&gt;Before introducing virtual threads into production, monitor the application carefully.&lt;/p&gt;

&lt;p&gt;Important metrics include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Active virtual thread count.&lt;/li&gt;
&lt;li&gt;Request throughput.&lt;/li&gt;
&lt;li&gt;API response time (P95/P99).&lt;/li&gt;
&lt;li&gt;Database connection pool utilization.&lt;/li&gt;
&lt;li&gt;CPU utilization.&lt;/li&gt;
&lt;li&gt;Heap memory consumption.&lt;/li&gt;
&lt;li&gt;GC frequency and pause times.&lt;/li&gt;
&lt;li&gt;Downstream API latency.&lt;/li&gt;
&lt;li&gt;Thread pinning events.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Useful tools:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Java Flight Recorder (JFR).&lt;/li&gt;
&lt;li&gt;Java Mission Control (JMC).&lt;/li&gt;
&lt;li&gt;Thread dumps.&lt;/li&gt;
&lt;li&gt;Spring Boot Actuator.&lt;/li&gt;
&lt;li&gt;Micrometer and Prometheus.&lt;/li&gt;
&lt;li&gt;Grafana.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For Java 21, JFR includes virtual-thread-related events that help investigate pinning and scheduling behavior.&lt;/p&gt;




&lt;h2&gt;
  
  
  11. When Should Enterprises Adopt Virtual Threads?
&lt;/h2&gt;

&lt;p&gt;For enterprise Java applications, virtual threads are particularly useful when workloads are I/O-bound and use a blocking programming model.&lt;/p&gt;

&lt;p&gt;Examples include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Banking transaction APIs.&lt;/li&gt;
&lt;li&gt;Payment processing systems.&lt;/li&gt;
&lt;li&gt;Customer account services.&lt;/li&gt;
&lt;li&gt;Loan processing applications.&lt;/li&gt;
&lt;li&gt;Insurance policy services.&lt;/li&gt;
&lt;li&gt;Enterprise integration services.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Before migration, evaluate:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Current thread pool saturation.&lt;/li&gt;
&lt;li&gt;Request concurrency.&lt;/li&gt;
&lt;li&gt;Blocking I/O patterns.&lt;/li&gt;
&lt;li&gt;Database connection pool limits.&lt;/li&gt;
&lt;li&gt;Downstream API capacity.&lt;/li&gt;
&lt;li&gt;Performance under realistic load.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Run controlled load tests comparing platform threads and virtual threads.&lt;/p&gt;

&lt;p&gt;Measure throughput, latency, memory consumption, and resource utilization rather than assuming virtual threads will always improve performance.&lt;/p&gt;




&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Java Virtual Threads represent one of the most significant improvements to Java concurrency in recent years.&lt;/p&gt;

&lt;p&gt;They make it possible to write simple, blocking-style code while efficiently managing large numbers of concurrent tasks.&lt;/p&gt;

&lt;p&gt;For organizations running Spring Boot microservices, virtual threads provide an opportunity to improve concurrency without completely redesigning existing applications around asynchronous or reactive programming.&lt;/p&gt;

&lt;p&gt;But remember:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Virtual Threads improve scalability for I/O-bound workloads. They do not eliminate resource limits, replace proper system design, or make CPU-intensive operations faster.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;As Java developers and architects, understanding when and where to use virtual threads is becoming an important skill in designing scalable enterprise applications.&lt;/p&gt;




&lt;h2&gt;
  
  
  References
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://openjdk.org/jeps/444" rel="noopener noreferrer"&gt;JEP 444 – Virtual Threads&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.oracle.com/en/java/javase/21/" rel="noopener noreferrer"&gt;Java 21 Documentation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.spring.io/spring-boot/reference/features/task-execution-and-scheduling.html" rel="noopener noreferrer"&gt;Spring Boot Virtual Threads Documentation&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;&lt;strong&gt;What about your applications?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Are you planning to adopt Java Virtual Threads in your Spring Boot microservices, or are you still using traditional thread pools and CompletableFuture?&lt;/p&gt;

&lt;p&gt;Share your experience in the comments!&lt;/p&gt;

&lt;h1&gt;
  
  
  Java #Java21 #VirtualThreads #SpringBoot #Microservices #Concurrency #SoftwareArchitecture #BackendDevelopment #JVM
&lt;/h1&gt;

</description>
      <category>java</category>
      <category>java21</category>
      <category>concurrency</category>
      <category>springboot</category>
    </item>
    <item>
      <title>G1 GC vs ZGC: Understanding Modern Garbage Collectors in Java</title>
      <dc:creator>Ramanjaneyulu Boya</dc:creator>
      <pubDate>Mon, 16 Nov 2026 14:55:51 +0000</pubDate>
      <link>https://dev.to/ramthearchitect/g1-gc-vs-zgc-understanding-modern-garbage-collectors-in-java-4ehi</link>
      <guid>https://dev.to/ramthearchitect/g1-gc-vs-zgc-understanding-modern-garbage-collectors-in-java-4ehi</guid>
      <description>&lt;p&gt;Garbage Collection (GC) is one of the most important responsibilities of the Java Virtual Machine (JVM).&lt;/p&gt;

&lt;p&gt;As Java applications grow in complexity, managing memory efficiently becomes increasingly important. In enterprise applications, garbage collection can directly impact application response times, throughput, resource utilization, and overall system performance.&lt;/p&gt;

&lt;p&gt;Modern Java provides multiple garbage collectors, but two important choices for server-side applications are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;G1 Garbage Collector (G1 GC)&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Z Garbage Collector (ZGC)&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Both collectors aim to manage memory efficiently, but they approach garbage collection differently.&lt;/p&gt;

&lt;p&gt;So, which one should we choose for a production application?&lt;/p&gt;

&lt;p&gt;Let's understand their architecture, working mechanisms, differences, and practical use cases.&lt;/p&gt;




&lt;h2&gt;
  
  
  1. Understanding G1 Garbage Collector
&lt;/h2&gt;

&lt;p&gt;G1 stands for &lt;strong&gt;Garbage-First Garbage Collector&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;It became the default garbage collector in Java 9 and is designed to provide a balance between application throughput and predictable garbage collection pauses.&lt;/p&gt;

&lt;p&gt;Unlike traditional garbage collectors that divide the heap into large continuous memory areas, G1 divides the Java heap into multiple smaller regions.&lt;/p&gt;

&lt;p&gt;Each region can dynamically belong to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Eden Space&lt;/li&gt;
&lt;li&gt;Survivor Space&lt;/li&gt;
&lt;li&gt;Old Generation&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;G1 prioritizes regions containing more reclaimable garbage, which is where its name comes from.&lt;/p&gt;

&lt;h3&gt;
  
  
  How G1 GC works
&lt;/h3&gt;

&lt;p&gt;The G1 garbage collector follows several phases:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Young Generation Collection&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Collects objects from Eden and Survivor regions.&lt;/li&gt;
&lt;li&gt;Copies surviving objects into other regions.&lt;/li&gt;
&lt;li&gt;Reclaims unused regions.&lt;/li&gt;
&lt;li&gt;Uses Stop-The-World (STW) pauses.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;2. Concurrent Marking&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Identifies live objects in the old generation.&lt;/li&gt;
&lt;li&gt;Performs significant marking work concurrently with application threads.&lt;/li&gt;
&lt;li&gt;Helps determine which old-generation regions contain reclaimable memory.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;3. Mixed Garbage Collection&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Collects young-generation regions.&lt;/li&gt;
&lt;li&gt;Also collects selected old-generation regions.&lt;/li&gt;
&lt;li&gt;Prioritizes regions with more reclaimable space.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;4. Full GC&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;An expensive fallback operation.&lt;/li&gt;
&lt;li&gt;Can cause significantly longer application pauses.&lt;/li&gt;
&lt;li&gt;Ideally, production applications should avoid frequent Full GC events.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  G1 GC architecture
&lt;/h3&gt;

&lt;p&gt;Java Heap → Multiple Regions → Young Generation + Old Generation → Concurrent Marking → Mixed Collections → Memory Reclamation&lt;/p&gt;

&lt;p&gt;The main advantage of G1 is its ability to balance throughput and pause-time goals without requiring extensive manual tuning.&lt;/p&gt;




&lt;h2&gt;
  
  
  2. Understanding Z Garbage Collector (ZGC)
&lt;/h2&gt;

&lt;p&gt;ZGC is designed for applications where low latency is a major requirement.&lt;/p&gt;

&lt;p&gt;Unlike G1, ZGC performs almost all expensive garbage collection work concurrently with application execution.&lt;/p&gt;

&lt;p&gt;Its primary objective is to minimize application thread interruptions during garbage collection.&lt;/p&gt;

&lt;p&gt;ZGC is particularly useful for applications that:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Maintain large Java heaps.&lt;/li&gt;
&lt;li&gt;Require consistently low response times.&lt;/li&gt;
&lt;li&gt;Process high volumes of concurrent requests.&lt;/li&gt;
&lt;li&gt;Cannot tolerate significant GC-related latency spikes.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  How ZGC works
&lt;/h3&gt;

&lt;p&gt;ZGC uses several advanced JVM techniques:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Concurrent Marking&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;ZGC identifies live objects while application threads continue executing.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Concurrent Relocation&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Live objects can be moved to new memory locations concurrently with application execution.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Load Barriers&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;ZGC uses load barriers to maintain correct object references when objects are relocated.&lt;/p&gt;

&lt;p&gt;These mechanisms help the JVM manage references while garbage collection happens concurrently.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Reference Remapping&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;ZGC ensures that references to relocated objects are correctly resolved.&lt;/p&gt;

&lt;p&gt;The application does not need to understand where objects physically reside in the heap.&lt;/p&gt;

&lt;h3&gt;
  
  
  ZGC architecture
&lt;/h3&gt;

&lt;p&gt;Java Heap → Concurrent Marking → Live Object Identification → Concurrent Relocation → Reference Remapping → Memory Reclamation&lt;/p&gt;

&lt;p&gt;Unlike G1, ZGC aims to keep Stop-The-World pauses extremely short, generally below one millisecond.&lt;/p&gt;

&lt;p&gt;However, this does not mean the entire garbage collection cycle completes in one millisecond.&lt;/p&gt;

&lt;p&gt;The majority of its work happens concurrently.&lt;/p&gt;




&lt;h2&gt;
  
  
  3. G1 GC vs ZGC: Key Differences
&lt;/h2&gt;

&lt;p&gt;Let's compare both collectors.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Feature&lt;/th&gt;
&lt;th&gt;G1 GC&lt;/th&gt;
&lt;th&gt;ZGC&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Primary Goal&lt;/td&gt;
&lt;td&gt;Balanced throughput and latency&lt;/td&gt;
&lt;td&gt;Extremely low latency&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Architecture&lt;/td&gt;
&lt;td&gt;Region-based&lt;/td&gt;
&lt;td&gt;Concurrent, region-based&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Collection&lt;/td&gt;
&lt;td&gt;Mostly concurrent&lt;/td&gt;
&lt;td&gt;Almost entirely concurrent&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;STW Pauses&lt;/td&gt;
&lt;td&gt;Usually longer than ZGC&lt;/td&gt;
&lt;td&gt;Typically under 1 ms&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Heap Support&lt;/td&gt;
&lt;td&gt;Small to large heaps&lt;/td&gt;
&lt;td&gt;Large heaps, up to 16 TB in supported configurations&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Throughput&lt;/td&gt;
&lt;td&gt;Generally strong&lt;/td&gt;
&lt;td&gt;May involve additional CPU overhead&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;CPU Utilization&lt;/td&gt;
&lt;td&gt;Moderate GC overhead&lt;/td&gt;
&lt;td&gt;Can require more CPU resources&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Configuration&lt;/td&gt;
&lt;td&gt;Minimal tuning&lt;/td&gt;
&lt;td&gt;Minimal tuning&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Best For&lt;/td&gt;
&lt;td&gt;General enterprise applications&lt;/td&gt;
&lt;td&gt;Latency-sensitive applications&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Important:&lt;/strong&gt; Actual performance depends on heap size, live data, allocation rate, CPU availability, and workload characteristics. Neither collector is universally faster.&lt;/p&gt;




&lt;h2&gt;
  
  
  4. Understanding Stop-The-World (STW) Pauses
&lt;/h2&gt;

&lt;p&gt;One of the biggest differences between G1 and ZGC is how they handle application pauses.&lt;/p&gt;

&lt;p&gt;What exactly is a Stop-The-World pause?&lt;/p&gt;

&lt;p&gt;During certain garbage collection operations, the JVM temporarily pauses application threads to perform memory management safely.&lt;/p&gt;

&lt;p&gt;Consider an online banking application.&lt;/p&gt;

&lt;p&gt;Imagine an application processing thousands of payment requests per second.&lt;/p&gt;

&lt;p&gt;If garbage collection pauses application threads for 200 milliseconds, some requests may experience additional latency.&lt;/p&gt;

&lt;p&gt;This can impact:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;API response times&lt;/li&gt;
&lt;li&gt;Payment processing latency&lt;/li&gt;
&lt;li&gt;Transaction throughput&lt;/li&gt;
&lt;li&gt;Downstream service communication&lt;/li&gt;
&lt;li&gt;User experience&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;With G1, some garbage collection phases require Stop-The-World pauses.&lt;/p&gt;

&lt;p&gt;With ZGC, most expensive operations happen concurrently, significantly reducing the time application threads are paused.&lt;/p&gt;

&lt;p&gt;This makes ZGC particularly interesting for latency-sensitive backend services.&lt;/p&gt;




&lt;h2&gt;
  
  
  5. Real-World Example: Banking Microservices
&lt;/h2&gt;

&lt;p&gt;Consider an enterprise banking platform built using:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Java 21&lt;/li&gt;
&lt;li&gt;Spring Boot&lt;/li&gt;
&lt;li&gt;Microservices&lt;/li&gt;
&lt;li&gt;Apache Kafka&lt;/li&gt;
&lt;li&gt;PostgreSQL&lt;/li&gt;
&lt;li&gt;Redis&lt;/li&gt;
&lt;li&gt;Kubernetes / OpenShift&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Imagine three services:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Account Service&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Handles account information.&lt;/li&gt;
&lt;li&gt;Processes balance inquiries.&lt;/li&gt;
&lt;li&gt;Supports regular transactional workloads.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Payment Service&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Processes payment requests.&lt;/li&gt;
&lt;li&gt;Handles transaction validations.&lt;/li&gt;
&lt;li&gt;Requires predictable API response times.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Fraud Detection Service&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Processes high-volume transaction events.&lt;/li&gt;
&lt;li&gt;Performs fraud analysis.&lt;/li&gt;
&lt;li&gt;Maintains significant amounts of in-memory data.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Which garbage collector should we choose?&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Service&lt;/th&gt;
&lt;th&gt;Possible Choice&lt;/th&gt;
&lt;th&gt;Reason&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Account Service&lt;/td&gt;
&lt;td&gt;G1 GC&lt;/td&gt;
&lt;td&gt;Balanced throughput and latency&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Payment Service&lt;/td&gt;
&lt;td&gt;G1 or ZGC&lt;/td&gt;
&lt;td&gt;Depends on strict latency requirements&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Fraud Detection Service&lt;/td&gt;
&lt;td&gt;ZGC&lt;/td&gt;
&lt;td&gt;Worth evaluating for large heaps and latency-sensitive processing&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;These are starting points, not fixed rules.&lt;/p&gt;

&lt;p&gt;For example, if Payment Service experiences frequent GC-related latency spikes, ZGC may be worth evaluating.&lt;/p&gt;

&lt;p&gt;However, switching to ZGC without profiling and benchmarking is not a recommended production strategy.&lt;/p&gt;




&lt;h2&gt;
  
  
  6. How to Enable G1 GC and ZGC
&lt;/h2&gt;

&lt;p&gt;Let's look at the JVM options.&lt;/p&gt;

&lt;h3&gt;
  
  
  Enable G1 GC
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;java -XX:+UseG1GC -Xms4g -Xmx4g -jar application.jar
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;-XX:+UseG1GC&lt;/code&gt; enables G1.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;-Xms4g&lt;/code&gt; sets the initial heap size.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;-Xmx4g&lt;/code&gt; sets the maximum heap size.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;G1 is the default collector in modern HotSpot server configurations, so explicitly enabling it is usually unnecessary.&lt;/p&gt;

&lt;h3&gt;
  
  
  Enable ZGC
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;java -XX:+UseZGC -Xms4g -Xmx4g -jar application.jar
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This enables ZGC.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Important Java version consideration:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Java 21 introduced Generational ZGC as an experimental feature. It can be enabled with &lt;code&gt;-XX:+UseZGC -XX:+ZGenerational&lt;/code&gt; along with the required experimental VM option.&lt;/li&gt;
&lt;li&gt;Java 23 made Generational ZGC the default ZGC mode.&lt;/li&gt;
&lt;li&gt;Java 24 removed the non-generational ZGC mode. ZGC is generational by default.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This distinction is important when working with Java 21 versus newer Java releases.&lt;/p&gt;




&lt;h2&gt;
  
  
  7. Monitoring Garbage Collection
&lt;/h2&gt;

&lt;p&gt;Choosing a garbage collector is only the first step.&lt;/p&gt;

&lt;p&gt;Monitoring its behavior in production is equally important.&lt;/p&gt;

&lt;p&gt;Enable GC logging:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;-Xlog:gc*:file=gc.log:time,uptime,level,tags
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Monitor the following metrics:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;GC pause duration&lt;/li&gt;
&lt;li&gt;GC frequency&lt;/li&gt;
&lt;li&gt;Heap utilization&lt;/li&gt;
&lt;li&gt;Allocation rate&lt;/li&gt;
&lt;li&gt;Old-generation occupancy&lt;/li&gt;
&lt;li&gt;Concurrent GC activity&lt;/li&gt;
&lt;li&gt;CPU utilization&lt;/li&gt;
&lt;li&gt;Application response time&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Useful monitoring tools include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Java Flight Recorder (JFR)&lt;/li&gt;
&lt;li&gt;Java Mission Control (JMC)&lt;/li&gt;
&lt;li&gt;VisualVM&lt;/li&gt;
&lt;li&gt;Prometheus&lt;/li&gt;
&lt;li&gt;Grafana&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In Kubernetes or OpenShift environments, correlate JVM GC metrics with container CPU and memory utilization.&lt;/p&gt;

&lt;p&gt;This helps identify whether performance issues are caused by garbage collection, application allocation patterns, CPU throttling, or insufficient memory limits.&lt;/p&gt;




&lt;h2&gt;
  
  
  8. When Should You Choose G1 GC?
&lt;/h2&gt;

&lt;p&gt;Choose G1 when:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Your application needs a balance between throughput and latency.&lt;/li&gt;
&lt;li&gt;GC pauses of tens or hundreds of milliseconds are acceptable for your workload.&lt;/li&gt;
&lt;li&gt;You run typical enterprise Spring Boot applications.&lt;/li&gt;
&lt;li&gt;You want a mature, general-purpose collector.&lt;/li&gt;
&lt;li&gt;Your current GC performance meets your production SLAs.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  9. When Should You Choose ZGC?
&lt;/h2&gt;

&lt;p&gt;Consider ZGC when:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Your application has strict latency requirements.&lt;/li&gt;
&lt;li&gt;GC pauses are contributing to unacceptable p99 or p99.9 latency.&lt;/li&gt;
&lt;li&gt;Your application maintains a large live object set.&lt;/li&gt;
&lt;li&gt;You have sufficient CPU resources for concurrent GC operations.&lt;/li&gt;
&lt;li&gt;Benchmarking demonstrates measurable improvements over G1.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Remember: ZGC does not automatically fix memory leaks, excessive object allocation, or inefficient application code.&lt;/p&gt;




&lt;h2&gt;
  
  
  10. Final Thoughts
&lt;/h2&gt;

&lt;p&gt;G1 GC and ZGC solve the same fundamental problem but optimize for different application requirements.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;G1 GC&lt;/strong&gt; is an excellent general-purpose choice for enterprise Java applications where throughput and predictable pauses need to be balanced.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ZGC&lt;/strong&gt; is designed for workloads where minimizing garbage collection pauses is a critical requirement.&lt;/p&gt;

&lt;p&gt;As Java developers and architects, understanding garbage collection is not just about JVM configuration.&lt;/p&gt;

&lt;p&gt;It is about making informed architectural decisions that directly impact application performance, scalability, and reliability.&lt;/p&gt;

&lt;p&gt;The best garbage collector is not necessarily the newest one. It is the one that meets your application's performance requirements under real production workloads.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Understand the workload. Measure the performance. Choose the collector.&lt;/strong&gt;&lt;/p&gt;




&lt;h3&gt;
  
  
  References
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://docs.oracle.com/en/java/javase/25/gctuning/" rel="noopener noreferrer"&gt;Oracle Java Garbage Collection Tuning Guide&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.oracle.com/en/java/javase/25/gctuning/garbage-first-g1-garbage-collector1.html" rel="noopener noreferrer"&gt;G1 Garbage Collector&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.oracle.com/en/java/javase/24/gctuning/z-garbage-collector.html" rel="noopener noreferrer"&gt;Z Garbage Collector&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;&lt;strong&gt;Author:&lt;/strong&gt; Ramu Boya | Ram The Architect (RTA)&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Sharing practical Java, Spring Boot, Microservices, System Design, Cloud Architecture, and GenAI engineering insights.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Follow for more real-world Java and enterprise architecture discussions.&lt;/p&gt;

</description>
      <category>java</category>
      <category>jvm</category>
      <category>performance</category>
      <category>programming</category>
    </item>
    <item>
      <title>Understanding Garbage Collection in Modern Java: From Heap Memory to Production Performance</title>
      <dc:creator>Ramanjaneyulu Boya</dc:creator>
      <pubDate>Mon, 16 Nov 2026 14:07:24 +0000</pubDate>
      <link>https://dev.to/ramthearchitect/understanding-garbage-collection-in-modern-java-from-heap-memory-to-production-performance-5gn3</link>
      <guid>https://dev.to/ramthearchitect/understanding-garbage-collection-in-modern-java-from-heap-memory-to-production-performance-5gn3</guid>
      <description>&lt;p&gt;Garbage Collection (GC) is one of the most important features of the Java Virtual Machine (JVM).&lt;/p&gt;

&lt;p&gt;Java developers don't explicitly allocate and release memory like developers working with languages such as C or C++. The JVM manages object memory automatically through Garbage Collection.&lt;/p&gt;

&lt;p&gt;However, automatic memory management doesn't mean developers can ignore memory management.&lt;/p&gt;

&lt;p&gt;In real-world enterprise applications, especially high-throughput Spring Boot microservices, inefficient object allocation, memory leaks, excessive garbage collection, and poor JVM configuration can directly impact application performance and availability.&lt;/p&gt;

&lt;p&gt;Understanding how modern Java Garbage Collection works is essential for building scalable and reliable backend systems.&lt;/p&gt;

&lt;p&gt;Let's explore it from fundamentals to production-level considerations.&lt;/p&gt;




&lt;h2&gt;
  
  
  1. Understanding Java Heap Memory
&lt;/h2&gt;

&lt;p&gt;The JVM divides memory into different runtime areas. The Heap is where most Java objects are allocated.&lt;/p&gt;

&lt;p&gt;Consider the following example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;CustomerService&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;processCustomer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

        &lt;span class="nc"&gt;Customer&lt;/span&gt; &lt;span class="n"&gt;customer&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Customer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="n"&gt;customer&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;setId&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;101&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="n"&gt;customer&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;setName&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"John"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When &lt;code&gt;new Customer()&lt;/code&gt; executes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Memory is allocated for the Customer object in the heap.&lt;/li&gt;
&lt;li&gt;The local variable &lt;code&gt;customer&lt;/code&gt; holds a reference to the object.&lt;/li&gt;
&lt;li&gt;Once the method completes, the local reference goes out of scope.&lt;/li&gt;
&lt;li&gt;If no other reachable reference exists, the object becomes eligible for Garbage Collection.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Important: An object becoming eligible for GC does not mean it will be collected immediately.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. How Heap Memory Is Organized
&lt;/h2&gt;

&lt;p&gt;Traditionally, the JVM uses a generational memory model.&lt;/p&gt;

&lt;p&gt;The heap is conceptually divided into:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Young Generation&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Eden Space&lt;/li&gt;
&lt;li&gt;Survivor Space S0&lt;/li&gt;
&lt;li&gt;Survivor Space S1&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Old Generation&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Stores objects that survive multiple garbage collection cycles or are allocated directly into the old generation, depending on the collector and allocation behavior.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  How object allocation works
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;New objects are typically allocated in Eden.&lt;/li&gt;
&lt;li&gt;When Eden becomes full, a Minor GC occurs.&lt;/li&gt;
&lt;li&gt;Live objects are copied or otherwise preserved in survivor spaces.&lt;/li&gt;
&lt;li&gt;Objects that survive multiple collection cycles may be promoted to the Old Generation.&lt;/li&gt;
&lt;li&gt;Old Generation memory is reclaimed during appropriate collection cycles.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This generational approach is based on an important observation:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Most objects in Java applications have short lifetimes.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For example, temporary DTOs, request objects, intermediate collections, and serialization objects are frequently short-lived in Spring Boot applications.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. How Garbage Collection Works
&lt;/h2&gt;

&lt;p&gt;Garbage Collection identifies objects that are no longer reachable and reclaims their memory.&lt;/p&gt;

&lt;p&gt;The JVM uses GC Roots to determine object reachability.&lt;/p&gt;

&lt;p&gt;Common GC Roots include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Local variables and references in active thread stacks.&lt;/li&gt;
&lt;li&gt;Static references.&lt;/li&gt;
&lt;li&gt;Active Java threads.&lt;/li&gt;
&lt;li&gt;JNI references.&lt;/li&gt;
&lt;li&gt;Certain JVM internal references.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Consider:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;OrderService&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;processOrder&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

        &lt;span class="nc"&gt;Order&lt;/span&gt; &lt;span class="n"&gt;order&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Order&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;setOrderId&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1001&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="n"&gt;order&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;null&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After &lt;code&gt;order = null&lt;/code&gt;, the previously referenced object may become eligible for Garbage Collection, assuming no other references exist.&lt;/p&gt;

&lt;p&gt;The JVM uses reachability analysis rather than simply counting references.&lt;/p&gt;

&lt;p&gt;This distinction is important because circular references do not prevent objects from being collected if they are unreachable from GC Roots.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. Understanding Major Garbage Collectors in Modern Java
&lt;/h2&gt;

&lt;p&gt;Java has evolved significantly in its Garbage Collection implementations.&lt;/p&gt;

&lt;p&gt;Different collectors target different application requirements.&lt;/p&gt;

&lt;h3&gt;
  
  
  A. Serial GC
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Uses a single thread for garbage collection.&lt;/li&gt;
&lt;li&gt;Performs collection with application threads paused.&lt;/li&gt;
&lt;li&gt;Suitable for small applications with limited memory.&lt;/li&gt;
&lt;li&gt;Not generally preferred for high-throughput enterprise applications.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  B. Parallel GC
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Uses multiple threads for garbage collection.&lt;/li&gt;
&lt;li&gt;Focuses on maximizing application throughput.&lt;/li&gt;
&lt;li&gt;Can introduce longer Stop-The-World pauses.&lt;/li&gt;
&lt;li&gt;Useful for workloads where throughput is more important than low latency.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  C. G1 Garbage Collector
&lt;/h3&gt;

&lt;p&gt;G1 (Garbage-First) is a widely used collector and the default collector in modern server-class JVM configurations.&lt;/p&gt;

&lt;p&gt;Key characteristics:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Divides the heap into multiple regions.&lt;/li&gt;
&lt;li&gt;Prioritizes regions with more reclaimable memory.&lt;/li&gt;
&lt;li&gt;Performs concurrent marking.&lt;/li&gt;
&lt;li&gt;Supports configurable pause-time goals.&lt;/li&gt;
&lt;li&gt;Balances throughput and pause-time requirements.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Enable G1 explicitly:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;java -XX:+UseG1GC -jar application.jar
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Configure a pause-time goal:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;-XX:MaxGCPauseMillis=200
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note: This is a target, not a guaranteed maximum pause duration.&lt;/p&gt;

&lt;h3&gt;
  
  
  D. ZGC
&lt;/h3&gt;

&lt;p&gt;ZGC is designed for low-latency applications and supports very large heaps.&lt;/p&gt;

&lt;p&gt;Key characteristics:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Performs most GC work concurrently.&lt;/li&gt;
&lt;li&gt;Aims for very short pause times.&lt;/li&gt;
&lt;li&gt;Suitable for latency-sensitive workloads.&lt;/li&gt;
&lt;li&gt;Available in modern Java releases.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Enable ZGC:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;java -XX:+UseZGC -jar application.jar
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  E. Shenandoah GC
&lt;/h3&gt;

&lt;p&gt;Shenandoah is another low-pause garbage collector.&lt;/p&gt;

&lt;p&gt;Key characteristics:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Performs much of its work concurrently with application execution.&lt;/li&gt;
&lt;li&gt;Focuses on reducing pause times.&lt;/li&gt;
&lt;li&gt;Useful for latency-sensitive workloads.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Availability depends on the JDK distribution.&lt;/p&gt;

&lt;h2&gt;
  
  
  5. Understanding Stop-The-World (STW) Events
&lt;/h2&gt;

&lt;p&gt;Stop-The-World means application threads are temporarily paused while the JVM performs certain GC operations.&lt;/p&gt;

&lt;p&gt;For example, imagine a Spring Boot application processing 5,000 requests per second.&lt;/p&gt;

&lt;p&gt;If a GC pause temporarily stops application threads:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Requests may experience increased latency.&lt;/li&gt;
&lt;li&gt;Response times may become unpredictable.&lt;/li&gt;
&lt;li&gt;Request queues may grow.&lt;/li&gt;
&lt;li&gt;Downstream services may experience timeouts.&lt;/li&gt;
&lt;li&gt;Overall throughput may decrease.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Not every GC phase is Stop-The-World. Modern collectors such as G1, ZGC, and Shenandoah perform significant work concurrently.&lt;/p&gt;

&lt;p&gt;The objective is to balance memory reclamation, application throughput, and pause-time requirements.&lt;/p&gt;

&lt;h2&gt;
  
  
  6. Memory Leaks in Java: Why They Still Happen
&lt;/h2&gt;

&lt;p&gt;One common misconception is that Java cannot have memory leaks because it has Garbage Collection.&lt;/p&gt;

&lt;p&gt;Java applications can absolutely experience memory leaks.&lt;/p&gt;

&lt;p&gt;A memory leak occurs when objects are no longer needed but remain reachable through references.&lt;/p&gt;

&lt;p&gt;Common causes include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Static collections retaining unnecessary objects.&lt;/li&gt;
&lt;li&gt;Improper cache management.&lt;/li&gt;
&lt;li&gt;Unclosed resources.&lt;/li&gt;
&lt;li&gt;Event listeners that are never removed.&lt;/li&gt;
&lt;li&gt;ThreadLocal variables retaining references.&lt;/li&gt;
&lt;li&gt;Unbounded queues.&lt;/li&gt;
&lt;li&gt;Incorrectly managed application sessions.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;CustomerCache&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="kt"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Customer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="no"&gt;CUSTOMERS&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
            &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;addCustomer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Customer&lt;/span&gt; &lt;span class="n"&gt;customer&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="no"&gt;CUSTOMERS&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;customer&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If customers are continuously added without removing unnecessary entries, the collection keeps references to those objects.&lt;/p&gt;

&lt;p&gt;The GC cannot reclaim them while they remain reachable.&lt;/p&gt;

&lt;p&gt;In production applications, this can eventually lead to:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;java.lang.OutOfMemoryError: Java heap space
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  7. Monitoring Garbage Collection in Production
&lt;/h2&gt;

&lt;p&gt;Monitoring GC is critical for enterprise Java applications.&lt;/p&gt;

&lt;p&gt;Some useful JVM options and tools include:&lt;/p&gt;

&lt;h3&gt;
  
  
  Enable GC logging
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;-Xlog:gc*:file=gc.log:time,uptime,level,tags
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This generates detailed GC logs that help identify:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;GC frequency.&lt;/li&gt;
&lt;li&gt;Pause duration.&lt;/li&gt;
&lt;li&gt;Heap utilization.&lt;/li&gt;
&lt;li&gt;Memory allocation patterns.&lt;/li&gt;
&lt;li&gt;Collection behavior.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Useful JVM diagnostic tools
&lt;/h3&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Tool&lt;/th&gt;
&lt;th&gt;Purpose&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;jstat&lt;/td&gt;
&lt;td&gt;Monitor GC statistics&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;jcmd&lt;/td&gt;
&lt;td&gt;JVM diagnostic commands&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;jmap&lt;/td&gt;
&lt;td&gt;Heap information and dumps&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Java Flight Recorder&lt;/td&gt;
&lt;td&gt;Analyze runtime behavior&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Java Mission Control&lt;/td&gt;
&lt;td&gt;Analyze JVM performance&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;VisualVM&lt;/td&gt;
&lt;td&gt;Monitor heap and threads&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;jcmd &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;pid&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; GC.heap_info
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Generate a heap dump:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;jcmd &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;pid&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; GC.heap_dump heapdump.hprof
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Heap dumps can be analyzed using tools such as Eclipse MAT to identify memory retention and potential leaks.&lt;/p&gt;

&lt;h2&gt;
  
  
  8. Garbage Collection in Spring Boot Microservices
&lt;/h2&gt;

&lt;p&gt;Consider a banking application with multiple Spring Boot microservices:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Customer Service&lt;/li&gt;
&lt;li&gt;Account Service&lt;/li&gt;
&lt;li&gt;Payment Service&lt;/li&gt;
&lt;li&gt;Transaction Service&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Each service has its own JVM and memory allocation.&lt;/p&gt;

&lt;p&gt;During high transaction volumes, services may create thousands of temporary objects.&lt;/p&gt;

&lt;p&gt;Examples include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Request and response DTOs.&lt;/li&gt;
&lt;li&gt;JSON serialization objects.&lt;/li&gt;
&lt;li&gt;Database result mappings.&lt;/li&gt;
&lt;li&gt;Kafka consumer records.&lt;/li&gt;
&lt;li&gt;Temporary collections.&lt;/li&gt;
&lt;li&gt;Business validation objects.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If object allocation increases significantly, GC activity may also increase.&lt;/p&gt;

&lt;p&gt;This can affect application latency and resource utilization.&lt;/p&gt;

&lt;h3&gt;
  
  
  Production optimization considerations
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;Monitor heap utilization and allocation rates.&lt;/li&gt;
&lt;li&gt;Identify memory leaks using heap dumps.&lt;/li&gt;
&lt;li&gt;Analyze GC logs and pause times.&lt;/li&gt;
&lt;li&gt;Select a collector based on workload requirements.&lt;/li&gt;
&lt;li&gt;Configure container memory limits appropriately.&lt;/li&gt;
&lt;li&gt;Avoid unnecessary object creation in frequently executed code paths.&lt;/li&gt;
&lt;li&gt;Monitor CPU utilization alongside GC activity.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;For Kubernetes or OpenShift deployments, JVM memory configuration must also account for container memory limits.&lt;/p&gt;

&lt;p&gt;For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;-Xms512m
-Xmx2g
-XX:+UseG1GC
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;These are illustrative values, not universal production settings.&lt;/p&gt;

&lt;p&gt;Remember that JVM process memory includes more than Java heap memory. Metaspace, thread stacks, direct buffers, code cache, and other native allocations also consume memory.&lt;/p&gt;

&lt;h2&gt;
  
  
  9. Practical Interview Questions
&lt;/h2&gt;

&lt;p&gt;Here are some important Garbage Collection questions for experienced Java developers.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Q1. What is the difference between Minor GC and Major GC?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Minor GC traditionally refers to collection of the Young Generation. Major GC is commonly used to describe Old Generation collection, although terminology varies across collectors and JVM implementations.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Q2. Can we force Garbage Collection in Java?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We can request it using:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;gc&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, the JVM is not guaranteed to execute Garbage Collection immediately.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Q3. Can Java applications have memory leaks?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Yes. Objects that are no longer logically required can remain reachable through references, preventing GC from reclaiming them.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Q4. What is the difference between G1 GC and ZGC?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;G1 balances throughput and predictable pause-time goals using region-based collection. ZGC focuses on very low pause times using concurrent garbage collection techniques.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Q5. What happens when Old Generation memory becomes full?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The collector attempts to reclaim memory. If sufficient memory cannot be recovered and the heap cannot expand, the application may eventually encounter an OutOfMemoryError.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Q6. What is the relationship between GC and application latency?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;GC pauses can temporarily stop application threads, increasing response times. Allocation pressure and CPU consumed by GC can also affect latency.&lt;/p&gt;




&lt;h2&gt;
  
  
  10. Final Thoughts
&lt;/h2&gt;

&lt;p&gt;Garbage Collection is not just a JVM background activity. It directly influences application performance, scalability, and reliability.&lt;/p&gt;

&lt;p&gt;For experienced Java developers, understanding GC means going beyond knowing Minor GC, Major GC, and heap memory.&lt;/p&gt;

&lt;p&gt;It means being able to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Understand object allocation and reachability.&lt;/li&gt;
&lt;li&gt;Identify memory leaks.&lt;/li&gt;
&lt;li&gt;Analyze GC logs.&lt;/li&gt;
&lt;li&gt;Interpret heap dumps.&lt;/li&gt;
&lt;li&gt;Choose appropriate garbage collectors.&lt;/li&gt;
&lt;li&gt;Optimize JVM configurations for production workloads.&lt;/li&gt;
&lt;li&gt;Diagnose memory-related performance issues in distributed applications.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;As Java continues to evolve, understanding modern Garbage Collection mechanisms becomes increasingly important for building high-performance enterprise applications.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The real goal is not to eliminate Garbage Collection. It is to design applications that work efficiently with the JVM's memory management.&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Author:&lt;/strong&gt; Ramu Boya&lt;/p&gt;

&lt;h1&gt;
  
  
  Java #Java21 #GarbageCollection #JVM #SpringBoot #Microservices #PerformanceEngineering #BackendDevelopment #SoftwareArchitecture
&lt;/h1&gt;

</description>
      <category>java</category>
      <category>jvm</category>
      <category>performance</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Java Memory Management Explained: Heap, Stack, Metaspace and Garbage Collection</title>
      <dc:creator>Ramanjaneyulu Boya</dc:creator>
      <pubDate>Sat, 14 Nov 2026 18:41:08 +0000</pubDate>
      <link>https://dev.to/ramthearchitect/java-memory-management-explained-heap-stack-metaspace-and-garbage-collection-2j38</link>
      <guid>https://dev.to/ramthearchitect/java-memory-management-explained-heap-stack-metaspace-and-garbage-collection-2j38</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Have you ever wondered what happens inside the JVM when you create a Java object?&lt;/p&gt;

&lt;p&gt;Consider a simple statement:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;Customer&lt;/span&gt; &lt;span class="n"&gt;customer&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Customer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Ramu"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It looks like a straightforward object creation. However, several things happen behind the scenes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The JVM allocates memory for the object.&lt;/li&gt;
&lt;li&gt;A reference to the object is maintained in the executing thread's stack frame.&lt;/li&gt;
&lt;li&gt;The object is stored in the heap.&lt;/li&gt;
&lt;li&gt;The JVM manages the object's lifecycle.&lt;/li&gt;
&lt;li&gt;When the object is no longer reachable, it becomes eligible for garbage collection.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Understanding these operations is essential for every Java developer, particularly when building high-performance enterprise applications.&lt;/p&gt;

&lt;p&gt;In production environments, improper memory management can lead to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;OutOfMemoryError&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Frequent garbage collection&lt;/li&gt;
&lt;li&gt;Application latency&lt;/li&gt;
&lt;li&gt;Increased CPU utilization&lt;/li&gt;
&lt;li&gt;Memory leaks&lt;/li&gt;
&lt;li&gt;Application crashes&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In this article, we'll explore Java memory management from the JVM perspective, using Java 21 examples and practical enterprise application scenarios.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Understanding JVM Memory Architecture
&lt;/h2&gt;

&lt;p&gt;The Java Virtual Machine divides memory into different runtime areas to manage application execution efficiently.&lt;/p&gt;

&lt;p&gt;Some memory areas are shared across application threads, while others are created separately for each thread.&lt;/p&gt;

&lt;p&gt;The major JVM runtime memory areas include:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Heap&lt;/li&gt;
&lt;li&gt;Java Stack&lt;/li&gt;
&lt;li&gt;Method Area&lt;/li&gt;
&lt;li&gt;Program Counter Register&lt;/li&gt;
&lt;li&gt;Native Method Stack&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Additionally, JVM implementations use native memory areas such as Metaspace and Code Cache.&lt;/p&gt;

&lt;h3&gt;
  
  
  JVM Memory Architecture
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fgmevm8jnasynwrahp00m.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fgmevm8jnasynwrahp00m.jpg" alt="Java heap memory divided into young generation, Eden, survivor spaces S0 and S1, and old generation" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let's understand each component.&lt;/p&gt;

&lt;h3&gt;
  
  
  1.1 Heap Memory
&lt;/h3&gt;

&lt;p&gt;Heap is the primary memory area where Java objects and arrays are allocated.&lt;/p&gt;

&lt;p&gt;Important characteristics:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Shared across application threads.&lt;/li&gt;
&lt;li&gt;Managed by the garbage collector.&lt;/li&gt;
&lt;li&gt;Stores objects created using &lt;code&gt;new&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Usually the largest JVM memory area.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;CustomerService&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;createCustomer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

        &lt;span class="nc"&gt;Customer&lt;/span&gt; &lt;span class="n"&gt;customer&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
                &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Customer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Ramu"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;customer&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getName&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;Customer&lt;/code&gt; object is allocated on the heap, while the local reference variable &lt;code&gt;customer&lt;/code&gt; resides in the executing method's stack frame.&lt;/p&gt;

&lt;h3&gt;
  
  
  1.2 Java Stack Memory
&lt;/h3&gt;

&lt;p&gt;Each thread has its own Java stack.&lt;/p&gt;

&lt;p&gt;Whenever a method is invoked, the JVM creates a stack frame.&lt;/p&gt;

&lt;p&gt;A stack frame contains:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Local variables&lt;/li&gt;
&lt;li&gt;Operand stack&lt;/li&gt;
&lt;li&gt;Runtime constant pool reference&lt;/li&gt;
&lt;li&gt;Method execution information&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;processPayment&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;amount&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;5000&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nc"&gt;Payment&lt;/span&gt; &lt;span class="n"&gt;payment&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
            &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Payment&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nf"&gt;validatePayment&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;payment&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;amount&lt;/code&gt; is a primitive local variable.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;payment&lt;/code&gt; is a local reference variable.&lt;/li&gt;
&lt;li&gt;The actual &lt;code&gt;Payment&lt;/code&gt; object is allocated on the heap.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Each method invocation creates a new stack frame, and the frame is removed when the method completes.&lt;/p&gt;

&lt;h3&gt;
  
  
  1.3 Metaspace
&lt;/h3&gt;

&lt;p&gt;Metaspace stores class metadata required by the JVM.&lt;/p&gt;

&lt;p&gt;It was introduced in Java 8, replacing PermGen.&lt;/p&gt;

&lt;p&gt;Examples of metadata include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Class structure information&lt;/li&gt;
&lt;li&gt;Method metadata&lt;/li&gt;
&lt;li&gt;Runtime constant pool information&lt;/li&gt;
&lt;li&gt;Field information&lt;/li&gt;
&lt;li&gt;Method bytecode-related metadata&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Unlike heap memory, Metaspace uses native memory.&lt;/p&gt;

&lt;p&gt;An important consideration is that excessive class loading or classloader retention can cause Metaspace-related memory problems.&lt;/p&gt;

&lt;h3&gt;
  
  
  1.4 Program Counter Register
&lt;/h3&gt;

&lt;p&gt;Each JVM thread maintains its own Program Counter (PC) register.&lt;/p&gt;

&lt;p&gt;It identifies the JVM instruction currently being executed by that thread.&lt;/p&gt;

&lt;h3&gt;
  
  
  1.5 Native Method Stack
&lt;/h3&gt;

&lt;p&gt;Native Method Stack supports execution of native methods, typically implemented using languages such as C or C++ through JNI.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Understanding Heap Memory Generations
&lt;/h2&gt;

&lt;p&gt;Heap memory is where most Java developers encounter garbage collection concepts.&lt;/p&gt;

&lt;p&gt;In a traditional generational heap model, memory is divided into:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Young Generation&lt;/li&gt;
&lt;li&gt;Old Generation&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The Young Generation is further divided into:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Eden Space&lt;/li&gt;
&lt;li&gt;Survivor Space S0&lt;/li&gt;
&lt;li&gt;Survivor Space S1&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ff5cpuvc4r1h651d0z4ns.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ff5cpuvc4r1h651d0z4ns.jpg" alt="Java garbage collection workflow showing GC roots, reachable objects, unreachable objects, marking and memory reclamation" width="800" height="409"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  2.1 Eden Space
&lt;/h3&gt;

&lt;p&gt;Most new objects are initially allocated in Eden.&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;Customer&lt;/span&gt; &lt;span class="n"&gt;customer&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
        &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Customer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Ramu"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The object is typically allocated in Eden when the JVM uses a generational collector.&lt;/p&gt;

&lt;h3&gt;
  
  
  2.2 Survivor Spaces
&lt;/h3&gt;

&lt;p&gt;Survivor spaces are used to hold objects that survive garbage collection in the Young Generation.&lt;/p&gt;

&lt;p&gt;The JVM uses two survivor spaces, conventionally called S0 and S1.&lt;/p&gt;

&lt;p&gt;Objects surviving a minor collection may move between survivor spaces.&lt;/p&gt;

&lt;h3&gt;
  
  
  2.3 Old Generation
&lt;/h3&gt;

&lt;p&gt;Objects that survive multiple young-generation collections may eventually be promoted to the Old Generation.&lt;/p&gt;

&lt;p&gt;Examples include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Long-lived application configuration objects&lt;/li&gt;
&lt;li&gt;Cached reference data&lt;/li&gt;
&lt;li&gt;Shared application-level objects&lt;/li&gt;
&lt;li&gt;Long-running session-related objects&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Promotion depends on collector-specific policies and object age and size; it is not simply a fixed rule that every object follows.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. How Garbage Collection Works
&lt;/h2&gt;

&lt;p&gt;Garbage Collection (GC) is the JVM's automatic memory management mechanism.&lt;/p&gt;

&lt;p&gt;Its primary responsibility is to identify objects that are no longer reachable and reclaim their memory.&lt;/p&gt;

&lt;p&gt;An object becomes eligible for garbage collection when it is no longer reachable through the JVM's active reference paths.&lt;/p&gt;

&lt;p&gt;For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;MemoryExample&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

        &lt;span class="nc"&gt;Customer&lt;/span&gt; &lt;span class="n"&gt;customer&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
                &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Customer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Ramu"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="n"&gt;customer&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;null&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After assigning &lt;code&gt;null&lt;/code&gt;, the object may become eligible for garbage collection, assuming no other references exist.&lt;/p&gt;

&lt;p&gt;Remember:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Eligible for garbage collection does not mean immediately garbage collected.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The JVM decides when collection occurs.&lt;/p&gt;

&lt;h3&gt;
  
  
  3.1 Garbage Collection Workflow
&lt;/h3&gt;

&lt;p&gt;A simplified way to understand garbage collection is through these stages:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Identify GC Roots.&lt;/li&gt;
&lt;li&gt;Determine reachable objects.&lt;/li&gt;
&lt;li&gt;Identify unreachable objects.&lt;/li&gt;
&lt;li&gt;Reclaim eligible memory.&lt;/li&gt;
&lt;li&gt;Perform collector-specific compaction or relocation where applicable.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F1mq0ttvoyt0kgrsg5tb3.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F1mq0ttvoyt0kgrsg5tb3.jpg" alt="Java garbage collection workflow showing GC roots, reachable objects, unreachable objects, marking and memory reclamation" width="800" height="409"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Common GC Roots include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Active thread stack references&lt;/li&gt;
&lt;li&gt;Static references&lt;/li&gt;
&lt;li&gt;JNI references&lt;/li&gt;
&lt;li&gt;Other JVM-managed references&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The actual algorithms differ between garbage collectors.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. Types of Garbage Collection
&lt;/h2&gt;

&lt;p&gt;Java provides multiple garbage collectors designed for different application requirements.&lt;/p&gt;

&lt;h3&gt;
  
  
  4.1 Serial Garbage Collector
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Uses a single thread for garbage collection.&lt;/li&gt;
&lt;li&gt;Suitable for small applications.&lt;/li&gt;
&lt;li&gt;Can introduce longer pauses as heap size increases.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  4.2 Parallel Garbage Collector
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Uses multiple threads for garbage collection.&lt;/li&gt;
&lt;li&gt;Focuses on application throughput.&lt;/li&gt;
&lt;li&gt;Useful for workloads where throughput is more important than minimizing individual pause times.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  4.3 G1 Garbage Collector
&lt;/h3&gt;

&lt;p&gt;G1 (Garbage First) is the default garbage collector for typical server-class configurations in modern Java.&lt;/p&gt;

&lt;p&gt;Important characteristics:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Divides heap into multiple regions.&lt;/li&gt;
&lt;li&gt;Supports concurrent marking.&lt;/li&gt;
&lt;li&gt;Prioritizes regions with more reclaimable memory.&lt;/li&gt;
&lt;li&gt;Aims to meet configurable pause-time goals.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  4.4 Z Garbage Collector (ZGC)
&lt;/h3&gt;

&lt;p&gt;ZGC is designed for low-latency applications.&lt;/p&gt;

&lt;p&gt;Important characteristics:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Performs much of its work concurrently.&lt;/li&gt;
&lt;li&gt;Aims to maintain very short GC pauses.&lt;/li&gt;
&lt;li&gt;Supports large heaps.&lt;/li&gt;
&lt;li&gt;Generational ZGC is available in Java 21 as an experimental feature.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Comparison
&lt;/h3&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Collector&lt;/th&gt;
&lt;th&gt;Primary focus&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Serial GC&lt;/td&gt;
&lt;td&gt;Simplicity&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Parallel GC&lt;/td&gt;
&lt;td&gt;Throughput&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;G1 GC&lt;/td&gt;
&lt;td&gt;Balanced performance&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;ZGC&lt;/td&gt;
&lt;td&gt;Low latency&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;The right collector depends on workload characteristics, heap size, latency requirements and available resources.&lt;/p&gt;

&lt;h2&gt;
  
  
  5. Understanding Java Memory-Related Errors
&lt;/h2&gt;

&lt;p&gt;Memory problems are common in enterprise applications, especially when applications process large datasets or handle high concurrent traffic.&lt;/p&gt;

&lt;h3&gt;
  
  
  5.1 OutOfMemoryError: Java Heap Space
&lt;/h3&gt;

&lt;p&gt;Occurs when the JVM cannot allocate additional objects in the heap.&lt;/p&gt;

&lt;p&gt;Common causes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Unbounded collections&lt;/li&gt;
&lt;li&gt;Excessive object creation&lt;/li&gt;
&lt;li&gt;Memory leaks&lt;/li&gt;
&lt;li&gt;Large data processing without pagination&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kt"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;byte&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="kt"&gt;byte&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1024&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;1024&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This continuously allocates memory until the JVM cannot satisfy another allocation.&lt;/p&gt;

&lt;h3&gt;
  
  
  5.2 OutOfMemoryError: Metaspace
&lt;/h3&gt;

&lt;p&gt;Can occur when the JVM cannot allocate additional class metadata.&lt;/p&gt;

&lt;p&gt;Common causes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Excessive dynamic class loading&lt;/li&gt;
&lt;li&gt;Classloader leaks&lt;/li&gt;
&lt;li&gt;Improper application redeployment patterns&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  5.3 StackOverflowError
&lt;/h3&gt;

&lt;p&gt;Occurs when a thread's stack is exhausted.&lt;/p&gt;

&lt;p&gt;A common cause is uncontrolled recursion.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;process&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nf"&gt;process&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This method continuously invokes itself without a termination condition.&lt;/p&gt;

&lt;h2&gt;
  
  
  6. Memory Leaks in Java Applications
&lt;/h2&gt;

&lt;p&gt;Java has automatic garbage collection, but that does not mean memory leaks are impossible.&lt;/p&gt;

&lt;p&gt;A memory leak happens when objects are no longer needed by the application but remain reachable through references.&lt;/p&gt;

&lt;p&gt;Consider this example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;CustomerCache&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="kt"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Customer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
            &lt;span class="no"&gt;CACHE&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;addCustomer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Customer&lt;/span&gt; &lt;span class="n"&gt;customer&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="no"&gt;CACHE&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;customer&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If customers are continuously added and never removed, the static collection retains references to them.&lt;/p&gt;

&lt;p&gt;The garbage collector cannot reclaim these objects while they remain reachable.&lt;/p&gt;

&lt;p&gt;Common causes of memory leaks:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Static collections&lt;/li&gt;
&lt;li&gt;Unbounded caches&lt;/li&gt;
&lt;li&gt;Improper ThreadLocal usage&lt;/li&gt;
&lt;li&gt;Event listener references&lt;/li&gt;
&lt;li&gt;Unclosed resources&lt;/li&gt;
&lt;li&gt;Classloader retention&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In production applications, memory leaks can gradually increase heap utilization and eventually cause service failures.&lt;/p&gt;

&lt;h2&gt;
  
  
  7. JVM Memory Monitoring and Troubleshooting
&lt;/h2&gt;

&lt;p&gt;Understanding JVM memory is only the first step.&lt;/p&gt;

&lt;p&gt;Production engineers must also know how to monitor and troubleshoot memory problems.&lt;/p&gt;

&lt;p&gt;Useful JVM tools include:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Tool&lt;/th&gt;
&lt;th&gt;Purpose&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;jps&lt;/td&gt;
&lt;td&gt;List running Java processes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;jstat&lt;/td&gt;
&lt;td&gt;Monitor JVM statistics&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;jmap&lt;/td&gt;
&lt;td&gt;Inspect heap and generate heap dumps&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;jstack&lt;/td&gt;
&lt;td&gt;Capture thread dumps&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;jcmd&lt;/td&gt;
&lt;td&gt;Execute diagnostic commands&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Java Flight Recorder&lt;/td&gt;
&lt;td&gt;Profile JVM activity&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Java Mission Control&lt;/td&gt;
&lt;td&gt;Analyze JVM recordings&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Example commands:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;jcmd &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;pid&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; GC.heap_info
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;jcmd &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;pid&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; GC.class_histogram
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;jcmd &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;pid&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; JFR.start &lt;span class="nv"&gt;duration&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;60s &lt;span class="nv"&gt;filename&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;recording.jfr
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For garbage collection logging in Java 21:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;-Xlog:gc*:file=gc.log:time,uptime,level,tags
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For heap dump generation when an OutOfMemoryError occurs:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;-XX:+HeapDumpOnOutOfMemoryError
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;These diagnostics help identify memory consumption patterns, allocation behavior and possible leaks.&lt;/p&gt;

&lt;h2&gt;
  
  
  8. JVM Memory Management in Real-World Banking Applications
&lt;/h2&gt;

&lt;p&gt;Consider a banking application built using Java 21, Spring Boot and microservices.&lt;/p&gt;

&lt;p&gt;The application processes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Customer information&lt;/li&gt;
&lt;li&gt;Account details&lt;/li&gt;
&lt;li&gt;Payment transactions&lt;/li&gt;
&lt;li&gt;Transaction history&lt;/li&gt;
&lt;li&gt;Fraud detection requests&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Imagine a payment service processing thousands of concurrent requests.&lt;/p&gt;

&lt;p&gt;Each request may create multiple temporary objects:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Request DTOs&lt;/li&gt;
&lt;li&gt;Validation objects&lt;/li&gt;
&lt;li&gt;Domain objects&lt;/li&gt;
&lt;li&gt;Database entities&lt;/li&gt;
&lt;li&gt;Response DTOs&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Most temporary objects become eligible for garbage collection after request processing completes.&lt;/p&gt;

&lt;p&gt;However, application-level caches, shared collections and long-lived references may retain objects for much longer.&lt;/p&gt;

&lt;h3&gt;
  
  
  Production considerations
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;Set appropriate JVM heap limits.&lt;/li&gt;
&lt;li&gt;Monitor heap utilization and GC pause times.&lt;/li&gt;
&lt;li&gt;Avoid unbounded in-memory collections.&lt;/li&gt;
&lt;li&gt;Use pagination for large database queries.&lt;/li&gt;
&lt;li&gt;Profile object allocation patterns.&lt;/li&gt;
&lt;li&gt;Configure container memory limits carefully.&lt;/li&gt;
&lt;li&gt;Monitor application memory and container memory independently.&lt;/li&gt;
&lt;li&gt;Capture heap dumps when investigating memory leaks.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;For applications running on Kubernetes or OpenShift, remember that the JVM operates within container memory constraints.&lt;/p&gt;

&lt;p&gt;For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;-XX:MaxRAMPercentage=75.0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This allows the JVM to calculate its maximum heap based on the available memory it detects, subject to the JVM and container configuration.&lt;/p&gt;

&lt;p&gt;The remaining container memory must also accommodate Metaspace, thread stacks, direct buffers, code cache and other native allocations.&lt;/p&gt;

&lt;h2&gt;
  
  
  9. JVM Memory Tuning in Java 21
&lt;/h2&gt;

&lt;p&gt;Some useful JVM options include:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;JVM option&lt;/th&gt;
&lt;th&gt;Purpose&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;-Xms&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Initial heap size&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;-Xmx&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Maximum heap size&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;-Xss&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Thread stack size&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;-XX:+UseG1GC&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Enable G1 GC&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;-XX:+UseZGC&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Enable ZGC&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;-XX:MaxMetaspaceSize&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Set Metaspace limit&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;-XX:MaxRAMPercentage&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Set maximum heap percentage relative to detected RAM&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;java \
-Xms2g \
-Xmx4g \
-XX:+UseG1GC \
-Xlog:gc*:file=gc.log \
-jar banking-service.jar
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Important: JVM tuning should be based on actual workload measurements rather than blindly applying configuration values.&lt;/p&gt;

&lt;h2&gt;
  
  
  10. Best Practices for Java Memory Management
&lt;/h2&gt;

&lt;p&gt;Here are some practical guidelines for enterprise Java applications:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Avoid unnecessary object creation in performance-critical paths.&lt;/li&gt;
&lt;li&gt;Prefer bounded caches over unbounded collections.&lt;/li&gt;
&lt;li&gt;Use pagination for large database operations.&lt;/li&gt;
&lt;li&gt;Close resources using try-with-resources.&lt;/li&gt;
&lt;li&gt;Avoid retaining unnecessary references.&lt;/li&gt;
&lt;li&gt;Monitor garbage collection regularly.&lt;/li&gt;
&lt;li&gt;Understand container memory limits.&lt;/li&gt;
&lt;li&gt;Use heap dumps and profiling tools during troubleshooting.&lt;/li&gt;
&lt;li&gt;Select garbage collectors based on application requirements.&lt;/li&gt;
&lt;li&gt;Measure performance before and after tuning.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Java memory management is much more than understanding Heap, Stack and Garbage Collection.&lt;/p&gt;

&lt;p&gt;It is about understanding how the JVM allocates objects, manages their lifecycle, identifies unreachable references and reclaims memory efficiently.&lt;/p&gt;

&lt;p&gt;For enterprise applications, especially banking and financial systems, effective memory management directly influences application stability, performance, scalability and reliability.&lt;/p&gt;

&lt;p&gt;As Java developers and architects, understanding JVM internals helps us build applications that are not only functional but also production-ready.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Keep learning. Keep building. Keep architecting.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;— Ram The Architect (RTA)&lt;/p&gt;




&lt;h3&gt;
  
  
  Further Reading and Resources
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Java 21 Documentation: &lt;a href="https://docs.oracle.com/en/java/javase/21/" rel="noopener noreferrer"&gt;https://docs.oracle.com/en/java/javase/21/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Java Virtual Machine Specification: &lt;a href="https://docs.oracle.com/javase/specs/jvms/se21/html/" rel="noopener noreferrer"&gt;https://docs.oracle.com/javase/specs/jvms/se21/html/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Java Garbage Collection Documentation: &lt;a href="https://docs.oracle.com/en/java/javase/21/gctuning/" rel="noopener noreferrer"&gt;https://docs.oracle.com/en/java/javase/21/gctuning/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;GitHub: &lt;a href="https://github.com/Ramu-fsd" rel="noopener noreferrer"&gt;https://github.com/Ramu-fsd&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Discussion
&lt;/h3&gt;

&lt;p&gt;What garbage collector do you primarily use in your production Java applications — G1 GC, Parallel GC or ZGC?&lt;/p&gt;

&lt;p&gt;Have you encountered an OutOfMemoryError or a memory leak in a production environment? Share your experience in the comments.&lt;/p&gt;

</description>
      <category>java</category>
      <category>jvm</category>
      <category>programming</category>
      <category>performance</category>
    </item>
  </channel>
</rss>
