<?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: Nikhil Amin</title>
    <description>The latest articles on DEV Community by Nikhil Amin (@nikhil-amin).</description>
    <link>https://dev.to/nikhil-amin</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.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F546854%2F9cc6f74f-5502-496e-984b-bda0075b9f26.jpg</url>
      <title>DEV Community: Nikhil Amin</title>
      <link>https://dev.to/nikhil-amin</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/nikhil-amin"/>
    <language>en</language>
    <item>
      <title>CH-07: The Encrypted Enigma — Jai &amp; Veeru vs. The Key of Secrets</title>
      <dc:creator>Nikhil Amin</dc:creator>
      <pubDate>Sun, 08 Jun 2025 00:30:00 +0000</pubDate>
      <link>https://dev.to/nikhil-amin/ch-07-the-encrypted-enigma-jai-veeru-vs-the-key-of-secrets-3i4i</link>
      <guid>https://dev.to/nikhil-amin/ch-07-the-encrypted-enigma-jai-veeru-vs-the-key-of-secrets-3i4i</guid>
      <description>&lt;p&gt;The digital world was no place for the careless. Every system, every login, every transaction had to be shielded, encrypted, and fortified. Jai and Veeru, the legendary duo of developers, had seen many challenges before — but today’s mission was different.&lt;/p&gt;

&lt;p&gt;They stood before The Vault of Authentication, a cyber fortress protecting the most precious asset of modern applications: Secure Access.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;“This is it, Veeru,”&lt;/em&gt; Jai said, adjusting his glasses. &lt;em&gt;“No one gets in without the right credentials.”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;“Or out, if they mess up,”&lt;/em&gt; Veeru added, eyeing the firewall flickering with cryptographic defenses.&lt;/p&gt;

&lt;p&gt;Their mission was simple: Break in — but the right way.&lt;/p&gt;




&lt;h3&gt;
  
  
  The Challenge: Authentication vs. Authorization
&lt;/h3&gt;

&lt;p&gt;As they approached the vault’s interface, a booming voice echoed:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;🚨 “IDENTIFY YOURSELVES.” 🚨&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Jai confidently stepped forward. &lt;em&gt;“I’m Jai. That’s Veeru. We built half the code for this place.”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ACCESS DENIED.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Veeru smirked. &lt;em&gt;“Classic mistake, Jai. Authentication isn’t enough. We need authorization too.”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai raised an eyebrow. &lt;em&gt;“Authentication proves who we are. Authorization proves what we can do.”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;“Exactly! Think of it like entering a stadium. Your ticket (authentication) gets you inside, but your seat number (authorization) determines where you sit.”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai sighed. &lt;em&gt;“Alright, let’s do this properly.”&lt;/em&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  The Solution: JWT, OAuth2 &amp;amp; Spring Security
&lt;/h2&gt;

&lt;p&gt;To gain access, they needed three powerful tools:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;JWT (JSON Web Token):&lt;/strong&gt; Their digital passport, cryptographically signed to ensure nobody could tamper with it.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;OAuth2:&lt;/strong&gt; The system that granted access without exposing passwords.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Spring Security:&lt;/strong&gt; The guardian of the vault, validating every request before letting anyone in.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Veeru pulled out a JWT token from his pocket. &lt;em&gt;“This is our key.”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai inspected it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "alg": "HS256",
  "typ": "JWT"
}
{
  "sub": "Jai",
  "role": "admin",
  "exp": 1717248000
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;“The server will check the signature. If it’s valid, we’re in,”&lt;/em&gt; Veeru said.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;“Wait, what if someone steals this token?”&lt;/em&gt; Jai asked.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;“That’s why OAuth2 comes in! It issues short-lived access tokens and refresh tokens to maintain security.”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;They input the JWT into the vault’s system.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ACCESS GRANTED. ✅&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The doors swung open. They had cracked the code of secure authentication!&lt;/p&gt;




&lt;h2&gt;
  
  
  Cliffhanger: The Man-in-the-Middle Attack!
&lt;/h2&gt;

&lt;p&gt;Just as they stepped inside, the alarm blared again.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;“Unauthorized access detected!”&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A shadowy figure intercepted their request logs. Someone was trying to hijack their session!&lt;/p&gt;

&lt;p&gt;&lt;em&gt;“The tokens… they’ve been compromised!”&lt;/em&gt; Jai whispered.&lt;/p&gt;

&lt;p&gt;Veeru clenched his fists. &lt;em&gt;“We’re dealing with a Man-in-the-Middle Attack!”&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;📖 &lt;em&gt;To be continued…&lt;/em&gt; 🚀&lt;/p&gt;




&lt;h2&gt;
  
  
  💡Key Takeaways from This Chapter
&lt;/h2&gt;

&lt;p&gt;✔ &lt;strong&gt;Authentication ≠ Authorization:&lt;/strong&gt; Authentication verifies who you are; authorization verifies what you can do.&lt;br&gt;
✔ &lt;strong&gt;JWT (JSON Web Token):&lt;/strong&gt; A self-contained token ensuring secure, tamper-proof authentication.&lt;br&gt;
✔ &lt;strong&gt;OAuth2:&lt;/strong&gt; A secure way to grant limited access to applications without exposing passwords.&lt;br&gt;
✔ &lt;strong&gt;Spring Security:&lt;/strong&gt; Provides a framework to enforce authentication and authorization at every request.&lt;/p&gt;

</description>
      <category>java</category>
      <category>programming</category>
    </item>
    <item>
      <title>CH-06: The Echo of Events — Jai &amp; Veeru vs. The Microservices Mayhem</title>
      <dc:creator>Nikhil Amin</dc:creator>
      <pubDate>Sun, 01 Jun 2025 00:30:00 +0000</pubDate>
      <link>https://dev.to/nikhil-amin/ch-06-the-echo-of-events-jai-veeru-vs-the-microservices-mayhem-1mch</link>
      <guid>https://dev.to/nikhil-amin/ch-06-the-echo-of-events-jai-veeru-vs-the-microservices-mayhem-1mch</guid>
      <description>&lt;p&gt;It was a peaceful morning — until it wasn’t.&lt;/p&gt;

&lt;p&gt;Jai and Veeru had just pushed their latest update to production when alerts started flooding in.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;🚨 Service Down! 🚨&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;🚨 Database Overload! 🚨&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;🚨 API Latency Spike! 🚨&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Veeru panicked. &lt;em&gt;“What the hell is happening?! We just deployed a small feature!”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai grabbed his coffee. &lt;em&gt;“Looks like we triggered a microservices meltdown…”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Their system, which relied on REST APIs for communication, was now buckling under high traffic. The database was overwhelmed with requests, leading to timeouts, bottlenecks, and service failures.&lt;/p&gt;

&lt;p&gt;Veeru groaned. &lt;em&gt;“Jai… is this how big tech companies handle millions of users?”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai smirked. &lt;em&gt;“Not even close. It’s time to introduce you to event-driven microservices.”&lt;/em&gt;&lt;/p&gt;


&lt;h2&gt;
  
  
  The Problem: REST-Based Microservices Can’t Handle Scale
&lt;/h2&gt;

&lt;p&gt;Veeru scratched his head. &lt;em&gt;“But we already have a microservices architecture. Why is it failing?”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai explained, _“Our services communicate synchronously using REST APIs. But what happens when:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;✅ Traffic surges?&lt;/li&gt;
&lt;li&gt;✅ A service fails?&lt;/li&gt;
&lt;li&gt;✅ Requests pile up faster than they can be processed?”&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Veeru nodded. “It creates a domino effect, slowing everything down!”_&lt;/p&gt;

&lt;p&gt;Jai pulled up a diagram.&lt;/p&gt;

&lt;p&gt;🛑 &lt;strong&gt;Current REST-Based Flow:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;1️⃣ User sends a request to Service A.&lt;/li&gt;
&lt;li&gt;2️⃣ Service A calls Service B synchronously.&lt;/li&gt;
&lt;li&gt;3️⃣ Service B queries the database, which is already overloaded.&lt;/li&gt;
&lt;li&gt;4️⃣ Response takes too long → User faces a timeout.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;“This,”&lt;/em&gt; Jai said, pointing to the mess on the screen, &lt;em&gt;“is why big tech companies don’t rely on REST for everything.”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Veeru sighed. &lt;em&gt;“So, what’s the solution?”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai grinned. &lt;em&gt;“We decouple services using Apache Kafka.”&lt;/em&gt;&lt;/p&gt;


&lt;h2&gt;
  
  
  The Fix: Event-Driven Microservices with Kafka
&lt;/h2&gt;
&lt;h3&gt;
  
  
  Solution: Replacing REST Calls with Kafka Events
&lt;/h3&gt;

&lt;p&gt;With Kafka, instead of services waiting on each other, they communicate asynchronously using an event-driven approach.&lt;/p&gt;

&lt;p&gt;How It Works:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;✅ Service A publishes an event to Kafka (instead of calling Service B directly).&lt;/li&gt;
&lt;li&gt;✅ Kafka stores and streams the event to subscribers (Service B, C, etc.).&lt;/li&gt;
&lt;li&gt;✅ Service B processes the event when it’s ready, not when forced.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Veeru’s eyes lit up. &lt;em&gt;“That means no blocking and no direct dependencies!”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai nodded. &lt;em&gt;“Exactly! Now, if a service crashes, the events stay in Kafka until it recovers. No data loss!”&lt;/em&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  Implementing Kafka in Spring Boot
&lt;/h3&gt;

&lt;p&gt;Jai opened his code editor. &lt;em&gt;“Let’s convert our system to event-driven microservices.”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Add Kafka Dependencies&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;&amp;lt;dependency&amp;gt;
    &amp;lt;groupId&amp;gt;org.springframework.kafka&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;spring-kafka&amp;lt;/artifactId&amp;gt;
    &amp;lt;version&amp;gt;3.0.0&amp;lt;/version&amp;gt;
&amp;lt;/dependency&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 2: Create a Kafka Producer (Publishing Events)&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;@Service
public class OrderEventProducer {

    private final KafkaTemplate&amp;lt;String, String&amp;gt; kafkaTemplate;

    public OrderEventProducer(KafkaTemplate&amp;lt;String, String&amp;gt; kafkaTemplate) {
        this.kafkaTemplate = kafkaTemplate;
    }

    public void sendOrderEvent(String orderId) {
        kafkaTemplate.send("order-events", orderId);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 3: Create a Kafka Consumer (Processing Events)&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;@Service
public class OrderEventConsumer {

    @KafkaListener(topics = "order-events", groupId = "order-group")
    public void consume(String orderId) {
        System.out.println("Processing order: " + orderId);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Veeru whistled. &lt;em&gt;“That’s it? No more synchronous API calls?”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai grinned. &lt;em&gt;“Nope. Now our services talk to each other through Kafka. No more timeouts, database overload, or cascading failures.”&lt;/em&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  The Transformation: Before vs. After Kafka
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;BEFORE (REST-Based Microservices):&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;⏳ Services block while waiting for responses.&lt;/li&gt;
&lt;li&gt;⚠️ If one service fails, the whole chain collapses.&lt;/li&gt;
&lt;li&gt;📈 High traffic = database overload = system failure.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;AFTER (Event-Driven with Kafka):&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;⚡ Services communicate asynchronously.&lt;/li&gt;
&lt;li&gt;✅ Failures don’t break the whole system.&lt;/li&gt;
&lt;li&gt;📊 System auto-scales with high traffic.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  The Mystery Deepens…
&lt;/h2&gt;

&lt;p&gt;Just as they were about to celebrate, another alert popped up.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;🚨 Unauthorized Kafka Topic Detected: “shadow-events” 🚨&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Veeru’s stomach dropped. &lt;em&gt;“Jai… did we create that topic?”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai quickly checked the logs. Unknown events were flowing through Kafka — events that neither of them had written.&lt;/p&gt;

&lt;p&gt;Veeru gulped. &lt;em&gt;“Could someone be injecting rogue events into our system?”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai’s expression darkened. &lt;em&gt;“Or worse… have we just uncovered a Kafka security breach?”&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;📖 &lt;em&gt;To be continued…&lt;/em&gt; 🚀&lt;/p&gt;




&lt;h2&gt;
  
  
  💡Key Takeaways from This Chapter
&lt;/h2&gt;

&lt;p&gt;✔ &lt;strong&gt;Microservices should be decoupled&lt;/strong&gt; — REST isn’t scalable for high-traffic systems.&lt;br&gt;
✔ &lt;strong&gt;Use Apache Kafka&lt;/strong&gt; — It enables asynchronous event-driven communication.&lt;br&gt;
✔ &lt;strong&gt;Event Streams Reduce Failures&lt;/strong&gt; — If a service crashes, Kafka retains the event for processing later&lt;br&gt;
✔ &lt;strong&gt;Spring Boot + Kafka = Scalable Microservices&lt;/strong&gt; — Build resilient architectures that handle millions of users.&lt;/p&gt;

</description>
      <category>java</category>
      <category>programming</category>
    </item>
    <item>
      <title>CH-05: The Lost Code — Jai &amp; Veeru vs. The Ghost in the Repository</title>
      <dc:creator>Nikhil Amin</dc:creator>
      <pubDate>Sun, 25 May 2025 00:30:00 +0000</pubDate>
      <link>https://dev.to/nikhil-amin/ch-05-the-lost-code-jai-veeru-vs-the-ghost-in-the-repository-373a</link>
      <guid>https://dev.to/nikhil-amin/ch-05-the-lost-code-jai-veeru-vs-the-ghost-in-the-repository-373a</guid>
      <description>&lt;p&gt;Jai and Veeru were working late at night in their dimly lit office. The coffee cups were piling up, and Veeru was staring at his laptop screen, confused and frustrated.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;“Jai, something weird is happening!”&lt;/em&gt; he groaned.&lt;/p&gt;

&lt;p&gt;Jai, half-asleep, barely looked up. &lt;em&gt;“Is it your buggy code again?”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Veeru shook his head. &lt;em&gt;“No! Our app is supposed to log user activity, but somehow… data keeps disappearing!”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai frowned. &lt;em&gt;“What do you mean? Logs don’t just vanish!”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Veeru pointed at the screen. &lt;em&gt;“Look! Here’s a log of a user logging in… but when the request reaches the backend, poof! The data is gone!”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai’s eyes widened. This wasn’t just a bug. This was a ghost in the repository.&lt;/p&gt;




&lt;h2&gt;
  
  
  The Problem: Lost Data in Multi-Threaded Requests
&lt;/h2&gt;

&lt;p&gt;Veeru’s code was using ThreadLocal to store temporary data for each request:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private static final ThreadLocal&amp;lt;User&amp;gt; currentUser = new ThreadLocal&amp;lt;&amp;gt;();

public void handleRequest(User user) {
    currentUser.set(user);
    process();
}

public void process() {
    System.out.println("Processing user: " + currentUser.get().name());
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At first, it worked fine. But when the system scaled up and multiple requests came in, logs showed missing user data!&lt;/p&gt;

&lt;p&gt;Veeru scratched his head. &lt;em&gt;“Why is this happening, Jai?”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai sighed. &lt;em&gt;“Because ThreadLocal is broken in virtual threads!”&lt;/em&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  The Fix: Java 21’s Scoped Values
&lt;/h2&gt;

&lt;p&gt;&lt;em&gt;“Veeru, let me introduce you to Scoped Values — the modern replacement for ThreadLocal!”&lt;/em&gt; Jai said, rewriting the code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private static final ScopedValue&amp;lt;User&amp;gt; currentUser = ScopedValue.newInstance();

public void handleRequest(User user) {
    ScopedValue.where(currentUser, user).run(() -&amp;gt; process());
}

public void process() {
    System.out.println("Processing user: " + currentUser.get().name());
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Veeru’s jaw dropped. &lt;em&gt;“Wait… so Scoped Values don’t break in Virtual Threads?”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai nodded. &lt;em&gt;“Exactly! They are immutable, memory-efficient, and safe for concurrency. No more lost data!”&lt;/em&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  The Repository’s Dark Secret
&lt;/h2&gt;

&lt;p&gt;Just as Jai and Veeru were celebrating their victory, an alert flashed on the screen.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;“Unauthorized commit detected. Unknown changes pushed to the repository.”&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Veeru gulped. &lt;em&gt;“Jai… did you push any code?”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai shook his head. &lt;em&gt;“No… and we’re the only ones with access!”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;They checked the repository logs. A mysterious commit had overwritten part of their code — the same part handling user logs!&lt;/p&gt;

&lt;p&gt;Jai narrowed his eyes and whispered, &lt;em&gt;“Could it be… a supply chain attack?”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Veeru’s face turned pale. &lt;em&gt;“You mean like the Log4j exploit?”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai nodded. &lt;em&gt;“Exactly. If someone injected malicious code into our dependencies, we might have a security vulnerability in our system right now!”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Veeru’s hands trembled as he reached for his keyboard. &lt;em&gt;“Jai, we need to check our dependencies and Maven repositories — right now!”&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;📖 &lt;em&gt;To be continued…&lt;/em&gt; 🚀&lt;/p&gt;




&lt;h2&gt;
  
  
  💡Key Takeaways from This Chapter
&lt;/h2&gt;

&lt;p&gt;✔ &lt;strong&gt;ThreadLocal is outdated&lt;/strong&gt; — Switch to Scoped Values for better concurrency.&lt;br&gt;
✔ &lt;strong&gt;Scoped Values&lt;/strong&gt; — Immutable, thread-safe, and designed for modern Java applications.&lt;br&gt;
✔ &lt;strong&gt;Data Consistency&lt;/strong&gt; — Ensure no data is lost in multi-threaded environments.&lt;br&gt;
✔ &lt;strong&gt;Supply Chain Attacks&lt;/strong&gt; — Stay updated with security best practices in Java.&lt;/p&gt;

</description>
      <category>java</category>
      <category>programming</category>
    </item>
    <item>
      <title>CH-04 : The Singleton Paradox — Jai &amp; Veeru vs. The Multiverse of Objects</title>
      <dc:creator>Nikhil Amin</dc:creator>
      <pubDate>Sun, 18 May 2025 00:30:00 +0000</pubDate>
      <link>https://dev.to/nikhil-amin/ch-04-the-singleton-paradox-jai-veeru-vs-the-multiverse-of-objects-4cb1</link>
      <guid>https://dev.to/nikhil-amin/ch-04-the-singleton-paradox-jai-veeru-vs-the-multiverse-of-objects-4cb1</guid>
      <description>&lt;p&gt;Jai and Veeru were sipping chai on their terrace when Veeru suddenly blurted out, &lt;em&gt;“Jai, our app has a problem!”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai, halfway through a biscuit, raised an eyebrow. &lt;em&gt;“What now? Did you time-travel and forget your phone again?”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Veeru shook his head. &lt;em&gt;“Worse. Our app is creating too many objects! The memory usage is skyrocketing!”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai sighed. &lt;em&gt;“Ah, the Singleton problem. We need only one instance of an object, but Java keeps making more, wasting resources.”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Veeru scratched his head. &lt;em&gt;“So how do we fix it?”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai leaned forward, a mischievous smile forming. &lt;em&gt;“We use Java 21’s Record Patterns &amp;amp; Sealed Classes!”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Veeru blinked. &lt;em&gt;“Sounds fancy. Explain.”&lt;/em&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  The Problem: Too Many Instances
&lt;/h2&gt;

&lt;p&gt;Veeru had written this code for a Logger class:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Logger {
    public Logger() { System.out.println("New Logger Created!"); }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And every time he called &lt;code&gt;new Logger()&lt;/code&gt;, it created a new instance!&lt;/p&gt;

&lt;p&gt;Veeru frowned. &lt;em&gt;“But I only need one logger. Not a thousand!”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai smirked. &lt;em&gt;“That’s where Singleton Pattern comes in!”&lt;/em&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  The Fix: Singleton with Sealed Classes
&lt;/h2&gt;

&lt;p&gt;Jai rewrote the Logger class using Java 21’s Sealed Classes:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public sealed class Logger permits OnlyOne {
    private Logger() {} // Private Constructor  
    private static final Logger instance = new Logger();
    public static Logger getInstance() { return instance; }
}

final class OnlyOne extends Logger {} // Prevents more instances
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Veeru’s eyes widened. &lt;em&gt;“Wait… so now, even if someone tries to extend Logger, Java won’t allow it?"&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai nodded. &lt;em&gt;“Yes! Sealed classes restrict inheritance, enforcing one true instance!"&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Veeru clapped his hands. &lt;em&gt;“Jai, you’re a genius!”&lt;/em&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Record Patterns: The New Magic Trick
&lt;/h2&gt;

&lt;p&gt;Veeru frowned again. &lt;em&gt;“Okay, Singleton is solved. But what if we have too many duplicate objects, like users logging in with the same details?”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai chuckled. &lt;em&gt;“That’s where Record Patterns help. Instead of manually checking fields, Java 21 does it for us!”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Instead of writing this old, tedious way:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;record User(String name, String role) {}

User u = new User("Veeru", "Admin");
if (u.name().equals("Veeru") &amp;amp;&amp;amp; u.role().equals("Admin")) {
    System.out.println("Welcome, Admin!");
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Jai showed the modern approach:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;record User(String name, String role) {}

static void checkUser(User u) {
    if (u instanceof User("Veeru", "Admin")) {
        System.out.println("Welcome, Admin!");
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Veeru was stunned. &lt;em&gt;“That’s so much cleaner! No more repetitive .equals() calls?"&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai grinned. &lt;em&gt;“Yup! Java 21 makes code smarter and easier to read.”&lt;/em&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  The Real Paradox…
&lt;/h2&gt;

&lt;p&gt;Just as Jai and Veeru were celebrating their victory, Veeru’s phone beeped. It was an error message from their server.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;“Warning: Multiple instances detected. Memory overload imminent!”&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Veeru gulped. &lt;em&gt;“Jai… didn’t we just fix this?”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai stared at the screen, confused. &lt;em&gt;“Yes… which means something — or someone — is breaking the Singleton rule…”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;They exchanged a nervous glance.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;“Could it be… a rogue object?”&lt;/em&gt; Veeru whispered.&lt;/p&gt;

&lt;p&gt;Jai’s eyes narrowed. &lt;em&gt;“Only one way to find out.”&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;📖 &lt;em&gt;To be continued…&lt;/em&gt; 🚀&lt;/p&gt;




&lt;h2&gt;
  
  
  💡Key Takeaways from This Chapter
&lt;/h2&gt;

&lt;p&gt;✔ &lt;strong&gt;Sealed Classes&lt;/strong&gt; — Prevent unnecessary object creation.&lt;br&gt;
✔ &lt;strong&gt;Singleton with Permits&lt;/strong&gt; — Restrict inheritance for a true singleton pattern.&lt;br&gt;
✔ &lt;strong&gt;Record Patterns&lt;/strong&gt; — Cleaner, more readable pattern matching.&lt;br&gt;
✔ &lt;strong&gt;Better Performance&lt;/strong&gt; — Java 21 optimizes memory and CPU usage.&lt;/p&gt;

</description>
      <category>java</category>
      <category>programming</category>
    </item>
    <item>
      <title>CH-03 : The Phantom Thread – Jai &amp; Veeru vs. The Virtual Thread Mystery</title>
      <dc:creator>Nikhil Amin</dc:creator>
      <pubDate>Sun, 11 May 2025 00:30:00 +0000</pubDate>
      <link>https://dev.to/nikhil-amin/ch-03-the-phantom-thread-jai-veeru-vs-the-virtual-thread-mystery-3mhc</link>
      <guid>https://dev.to/nikhil-amin/ch-03-the-phantom-thread-jai-veeru-vs-the-virtual-thread-mystery-3mhc</guid>
      <description>&lt;p&gt;Jai and Veeru were back in action. This time, they were working on a high-performance chat application that needed to handle thousands of users simultaneously.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;“Veeru, this app must handle millions of messages per second!”&lt;/em&gt; Jai declared, typing away furiously.&lt;/p&gt;

&lt;p&gt;Veeru, munching on a samosa, shrugged. &lt;em&gt;“So what? We’ll just spawn thousands of threads like we always do!”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai’s fingers froze. He turned slowly. &lt;em&gt;“Did you just say… thousands of threads?”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Veeru grinned. &lt;em&gt;“Yes! More threads, more power, right?”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai sighed and pointed at his laptop screen. &lt;em&gt;“No, Veeru. Traditional threads in Java use OS threads, which are heavy. Too many of them will make our app slow, increasing memory usage and causing thread starvation.”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Veeru looked confused. &lt;em&gt;“So… what do we do? Reduce the threads?”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai smirked. &lt;em&gt;“Nope. We use Virtual Threads!”&lt;/em&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Enter Java 21’s Virtual Threads
&lt;/h2&gt;

&lt;p&gt;Jai quickly replaced this old, heavy thread creation method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ExecutorService executor = Executors.newFixedThreadPool(100); // Heavy OS threads  
executor.submit(() -&amp;gt; { 
    System.out.println("Processing request...");
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With this lightweight Virtual Thread approach:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {  
    executor.submit(() -&amp;gt; System.out.println("Processing request..."));
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Veeru’s jaw dropped. &lt;em&gt;“Wait… this creates thousands of threads without slowing down the system?”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai nodded. &lt;em&gt;“Yes! Virtual Threads are cheap, don’t block OS threads, and allow high scalability with minimal memory usage.”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Veeru clapped his hands. &lt;em&gt;“Jai, you’re a genius! This means we can handle millions of users without breaking our app!”&lt;/em&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Structured Concurrency — Fixing Messy Thread Management
&lt;/h2&gt;

&lt;p&gt;&lt;em&gt;“But wait, Jai,”&lt;/em&gt; Veeru frowned. &lt;em&gt;“Managing threads is always a headache. What if some threads finish early and others take forever?”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai grinned. &lt;em&gt;“Good question! Java 21 solves this with Structured Concurrency. Instead of tracking and managing each thread manually, we can group tasks together!”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Instead of this traditional, messy thread management:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ExecutorService executor = Executors.newFixedThreadPool(10);  
Future&amp;lt;String&amp;gt; future1 = executor.submit(() -&amp;gt; fetchData("user1"));  
Future&amp;lt;String&amp;gt; future2 = executor.submit(() -&amp;gt; fetchData("user2"));  
System.out.println(future1.get() + future2.get());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Jai showed Veeru this cleaner, structured concurrency approach:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {  
    var user1 = scope.fork(() -&amp;gt; fetchData("user1"));  
    var user2 = scope.fork(() -&amp;gt; fetchData("user2"));  
    scope.join();  
    System.out.println(user1.get() + user2.get());  
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Veeru was impressed. &lt;em&gt;“So now, if one thread fails, we can shut everything down safely, avoiding half-executed tasks?”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai nodded. &lt;em&gt;“Exactly! No more thread leaks or orphaned tasks.”&lt;/em&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  The Future of High-Performance Java Apps
&lt;/h2&gt;

&lt;p&gt;With Java 21’s Virtual Threads &amp;amp; Structured Concurrency, Jai and Veeru’s chat app became:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;✅ &lt;strong&gt;Ultra-fast&lt;/strong&gt; — Thousands of lightweight threads without crashing the system.&lt;/li&gt;
&lt;li&gt;✅ &lt;strong&gt;Memory-efficient&lt;/strong&gt; — No wasted resources on heavyweight OS threads.&lt;/li&gt;
&lt;li&gt;✅ &lt;strong&gt;Clean &amp;amp; Manageable&lt;/strong&gt; — Threads were grouped logically, preventing errors.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Veeru stretched his arms. &lt;em&gt;“Jai, this Java 21 update is better than a Bollywood plot twist!”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai laughed. &lt;em&gt;“Yes, my friend! Now, let’s launch our app — this time, without a thread crisis!”&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;📖 &lt;em&gt;To be continued…&lt;/em&gt; 🚀&lt;/p&gt;




&lt;h2&gt;
  
  
  💡Key Takeaways from This Chapter
&lt;/h2&gt;

&lt;p&gt;✔ &lt;strong&gt;Virtual Threads&lt;/strong&gt; — Lightweight, scalable, and perfect for high-performance apps.&lt;br&gt;
✔ &lt;strong&gt;Structured Concurrency&lt;/strong&gt; — Simplifies thread management, prevents failures.&lt;br&gt;
✔ &lt;strong&gt;Goodbye Heavy OS Threads&lt;/strong&gt; — More efficiency, fewer headaches!&lt;/p&gt;

</description>
      <category>java</category>
      <category>programming</category>
    </item>
    <item>
      <title>CH-02 : The Time Traveler’s Bug</title>
      <dc:creator>Nikhil Amin</dc:creator>
      <pubDate>Sun, 04 May 2025 00:30:00 +0000</pubDate>
      <link>https://dev.to/nikhil-amin/ch-02-the-time-travelers-bug-3el6</link>
      <guid>https://dev.to/nikhil-amin/ch-02-the-time-travelers-bug-3el6</guid>
      <description>&lt;p&gt;Jai leaned back in his chair, a smug grin on his face. &lt;em&gt;“Veeru, my friend, we’ve done it! The world’s first time-traveling app!”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Veeru, sipping his chai, raised an eyebrow. &lt;em&gt;“You sure this works? Last time, we ended up in 1975, and Gabbar stole my phone!”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai rolled his eyes. &lt;em&gt;“Relax. I’ve fixed all the bugs. Look, we just enter a date, and — “&lt;/em&gt; He typed &lt;strong&gt;&lt;em&gt;“March 30, 2025, 10:00 AM IST”&lt;/em&gt;&lt;/strong&gt; into the console and pressed enter.&lt;/p&gt;

&lt;p&gt;Poof! The screen flickered. The app showed &lt;strong&gt;March 29, 2025, 11:30 PM&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Veeru choked on his chai. &lt;em&gt;“Eh? That’s yesterday! What kind of time travel is this?!”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai’s confidence crumbled. He scanned the code, mumbling, &lt;em&gt;“Must be a daylight saving issue… Oh no.”&lt;/em&gt; His face turned pale. &lt;em&gt;“I used &lt;code&gt;java.util.Date&lt;/code&gt; and &lt;code&gt;SimpleDateFormat&lt;/code&gt;. The old Java date-time APIs!"&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Veeru blinked. &lt;em&gt;“So?”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai sighed. &lt;em&gt;“They don’t handle time zones properly! The app defaulted to UTC, ignoring IST.”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Veeru scratched his head. &lt;em&gt;“So, how do we fix it?”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai cracked his knuckles. &lt;em&gt;“We use &lt;code&gt;java.time&lt;/code&gt;! The modern API makes it easy."&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;He replaced:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse("2025-03-30 10:00:00");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



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

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
ZonedDateTime dateTime = LocalDateTime.parse("2025-03-30 10:00:00", formatter)
                           .atZone(ZoneId.of("Asia/Kolkata"));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Jai hit run. This time, the app correctly displayed &lt;strong&gt;March 30, 2025, 10:00 AM IST&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Veeru cheered. &lt;em&gt;“Now that’s time travel!”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai smirked. &lt;em&gt;“Lesson learned: Never mess with old Java date APIs. java.time is the future!"&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Veeru chuckled. &lt;em&gt;“Good. Now, let’s set it to 1975 again — I have unfinished business with Gabbar!”&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;📖 &lt;em&gt;To be continued…&lt;/em&gt; 🚀&lt;/p&gt;




&lt;h2&gt;
  
  
  💡 Key Takeaways from This Chapter
&lt;/h2&gt;

&lt;p&gt;✔ &lt;code&gt;java.util.Date&lt;/code&gt; &amp;amp; &lt;code&gt;SimpleDateFormat&lt;/code&gt; have time zone issues.&lt;br&gt;
✔ Use &lt;code&gt;java.time&lt;/code&gt; (&lt;strong&gt;LocalDateTime&lt;/strong&gt;, &lt;strong&gt;ZonedDateTime&lt;/strong&gt;) for correct time handling.&lt;br&gt;
✔ Always specify a **ZoneId **when working with date and time in Java.&lt;/p&gt;

</description>
      <category>java</category>
      <category>programming</category>
    </item>
    <item>
      <title>CH-01 : The Tale of Two Threads</title>
      <dc:creator>Nikhil Amin</dc:creator>
      <pubDate>Sun, 27 Apr 2025 00:30:00 +0000</pubDate>
      <link>https://dev.to/nikhil-amin/ch-01-the-tale-of-two-threads-4a31</link>
      <guid>https://dev.to/nikhil-amin/ch-01-the-tale-of-two-threads-4a31</guid>
      <description>&lt;h2&gt;
  
  
  The Beginning of a Great Project
&lt;/h2&gt;

&lt;p&gt;Jai and Veeru had been best friends since childhood. They had built sandcastles together, cracked math puzzles in school, and now, as software engineers, they were working on their most ambitious project yet: a personal finance tracking application.&lt;/p&gt;

&lt;p&gt;The plan was simple — Jai would handle the data processing and calculations, while Veeru would work on fetching and updating user transactions. They were confident, excited, and ready to conquer the tech world.&lt;/p&gt;

&lt;p&gt;But soon, chaos ensued.&lt;/p&gt;




&lt;h2&gt;
  
  
  The Race Condition Catastrophe
&lt;/h2&gt;

&lt;p&gt;It all started on a quiet Monday morning. Jai was deep in his code, running a loop to sum up the user’s total expenses. At the same time, Veeru, unaware of Jai’s calculations, updated the transaction list in real-time.&lt;/p&gt;

&lt;p&gt;And just like that… their program crashed.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;“Jai! What did you do? My updates aren’t reflecting properly!”&lt;/em&gt; Veeru frowned.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;“What did I do? You just modified the data while I was still processing it!”&lt;/em&gt; Jai shot back.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;“But… we’re working together, right?”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;“Yeah, but not like this! It’s like trying to count sheep while someone keeps adding more in the middle!”&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Jai pulled out his laptop and ran their latest test:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class SharedAccount {
    int balance = 0;

    void addExpense(int amount) {  
        balance += amount;  
    }
}

public class RaceConditionDemo {
    public static void main(String[] args) {
        SharedAccount account = new SharedAccount();

        Thread t1 = new Thread(() -&amp;gt; {
            for (int i = 0; i &amp;lt; 1000; i++) account.addExpense(10);
        });

        Thread t2 = new Thread(() -&amp;gt; {
            for (int i = 0; i &amp;lt; 1000; i++) account.addExpense(10);
        });

        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Final Balance: " + account.balance);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Veeru stared at the output. Instead of 20,000, they were getting random values — sometimes 18,920, sometimes 19,570.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;“Wait, what? The final balance isn’t consistent?”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;“Exactly,”&lt;/em&gt; Jai said, &lt;em&gt;“because both of us are modifying the same data at the same time without control. This is a race condition.”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;“Okay, so how do we fix it?”&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Jai smirked. &lt;em&gt;“Time to introduce some order.”&lt;/em&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  The Synchronization Spell — Preventing the Clash
&lt;/h2&gt;

&lt;p&gt;Jai took a deep breath. &lt;em&gt;“We need to synchronize access to the shared resource so only one thread can modify the balance at a time.”&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class SharedAccount {
    int balance = 0;

    synchronized void addExpense(int amount) { // Lock applied!
        balance += amount;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Veeru watched as Jai ran the updated code. Now, the final balance was always 20,000.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;“Whoa, so synchronized makes sure that only one of us works on the balance at a time!"&lt;/em&gt; Veeru said, amazed.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;“Exactly! It’s like locking the door while you’re in the room. I can’t come in and mess things up until you’re done.”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;“But wait… doesn’t this slow things down? If one of us is waiting, the other can’t do anything!”&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Jai nodded. &lt;em&gt;“You’re catching on fast! That’s called thread blocking. Synchronization solves one problem but introduces another — performance bottlenecks.”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Veeru frowned. &lt;em&gt;“So what do we do?”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai grinned. &lt;em&gt;“We call the Executor.”&lt;/em&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  The ExecutorService — The Manager of Chaos
&lt;/h2&gt;

&lt;p&gt;Jai leaned forward. &lt;em&gt;“Instead of manually handling threads, we can use ExecutorService — think of it as a manager who assigns work to available workers efficiently.”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;He wrote down the improved version:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class SharedAccount {
    int balance = 0;

    synchronized void addExpense(int amount) {
        balance += amount;
    }
}

public class ExecutorServiceDemo {
    public static void main(String[] args) {
        SharedAccount account = new SharedAccount();
        ExecutorService executor = Executors.newFixedThreadPool(2);

        for (int i = 0; i &amp;lt; 1000; i++) {
            executor.submit(() -&amp;gt; account.addExpense(10));
        }

        executor.shutdown();
        while (!executor.isTerminated()) {}

        System.out.println("Final Balance: " + account.balance);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Veeru’s eyes widened. &lt;em&gt;“So instead of us working on our own and messing things up, we now have a manager who keeps everything running smoothly?”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai nodded. &lt;em&gt;“Exactly. ExecutorService creates a pool of threads and reuses them efficiently instead of making new ones each time.”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Veeru grinned. &lt;em&gt;“Okay, I love this! But… can we do even better?”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai smirked. &lt;em&gt;“Of course. Let’s make it asynchronous.”&lt;/em&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  CompletableFuture — The Magic of Parallel Execution
&lt;/h2&gt;

&lt;p&gt;Jai typed rapidly. &lt;em&gt;“With CompletableFuture, we can run tasks in parallel, wait for them to finish, and even chain them together!"&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import java.util.concurrent.CompletableFuture;

public class CompletableFutureDemo {
    public static void main(String[] args) {
        CompletableFuture&amp;lt;Void&amp;gt; task1 = CompletableFuture.runAsync(() -&amp;gt; {
            System.out.println("Fetching transactions...");
        });

        CompletableFuture&amp;lt;Void&amp;gt; task2 = CompletableFuture.runAsync(() -&amp;gt; {
            System.out.println("Calculating expenses...");
        });

        task1.thenRun(task2).join();
        System.out.println("All tasks completed!");
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Veeru gasped. &lt;em&gt;“This is amazing! It’s like we’re both working in parallel, without blocking each other!”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai nodded. &lt;em&gt;“That’s the power of asynchronous programming. Tasks run independently, but we can still control their flow.”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Veeru grinned. &lt;em&gt;“So, first we learned synchronization to fix conflicts, then ExecutorService to manage work, and finally CompletableFuture for full parallelism!”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Jai stretched his arms. &lt;em&gt;“Exactly. And that, my friend, is how you handle multithreading and concurrency in Java.”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Veeru smiled. Their project was finally working smoothly.&lt;/p&gt;

&lt;p&gt;But little did they know… the next challenge was lurking right around the corner — Deadlocks.&lt;/p&gt;




&lt;p&gt;📖 &lt;em&gt;To be continued…&lt;/em&gt; 🚀&lt;/p&gt;




&lt;h2&gt;
  
  
  💡 Key Takeaways from This Chapter
&lt;/h2&gt;

&lt;p&gt;✔ &lt;strong&gt;Race Conditions&lt;/strong&gt; occur when multiple threads access shared data simultaneously.&lt;br&gt;
✔ &lt;strong&gt;Synchronized methods&lt;/strong&gt; prevent interference but may cause performance issues.&lt;br&gt;
✔ &lt;strong&gt;ExecutorService&lt;/strong&gt; efficiently manages threads and prevents overuse.&lt;br&gt;
✔ &lt;strong&gt;CompletableFuture&lt;/strong&gt; allows truly asynchronous execution, making programs faster.&lt;/p&gt;

</description>
      <category>java</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
