<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Manishkumar Modi on Medium]]></title>
        <description><![CDATA[Stories by Manishkumar Modi on Medium]]></description>
        <link>https://medium.com/@manishkumar.modi?source=rss-2d4491b2c635------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*OE0IUbVMZgF5V-oTlc0zzQ.jpeg</url>
            <title>Stories by Manishkumar Modi on Medium</title>
            <link>https://medium.com/@manishkumar.modi?source=rss-2d4491b2c635------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 08:34:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@manishkumar.modi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[From IntelliJ to VS Code ::: Setting Up Your First Java Spring Boot App (Step-by-Step Guide)]]></title>
            <link>https://medium.com/@manishkumar.modi/from-intellij-to-vs-code-setting-up-your-first-java-spring-boot-app-step-by-step-guide-695709fdff36?source=rss-2d4491b2c635------2</link>
            <guid isPermaLink="false">https://medium.com/p/695709fdff36</guid>
            <dc:creator><![CDATA[Manishkumar Modi]]></dc:creator>
            <pubDate>Sat, 18 Apr 2026 04:36:22 GMT</pubDate>
            <atom:updated>2026-04-18T04:42:57.476Z</atom:updated>
            <content:encoded><![CDATA[<p>When I first heard that many developers were trying Java development in Visual Studio Code, I was skeptical.</p><p>“Java in VS Code? That’s for JavaScript developers…”</p><p>But curiosity won. And what I discovered surprised me.</p><p>If you set it up right, VS Code can become a clean, fast, and surprisingly powerful environment for Spring Boot development — especially when paired with modern tools.</p><p>In this guide, I’ll walk you through exactly how to set up your Java Spring Boot application in VS Code using the steps you’ve already captured with screenshots.</p><p>🚀 Step 1: Install VS Code and Java Extensions</p><p>Start by installing Visual Studio Code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e5vZ_aOd7L3qpuTMqi-SPw.jpeg" /></figure><p>Once installed, the real magic comes from extensions.</p><p>Extension Pack for Java</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oEt9KCn92wNM0u1PH_rz7w.jpeg" /></figure><p>or Install Visual Studio Code for Java</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aoJxMi1eKHCpt6pGML0OPQ.jpeg" /></figure><p>👉 After installation, restart VS Code to ensure everything loads properly.</p><p>📦 Step 2: Clone Your Code Repository</p><p>Now that your environment is ready, it’s time to bring in your project.</p><p>Open VS Code and navigate to the <strong>Source Control</strong> section.</p><p>You’ll see an option to Clone Repository. Click on it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GKwb78Gp0Cv_ROTBPtO_cg.jpeg" /></figure><p>🔗 Step 3: Clone from GitHub</p><p>Paste your repository URL (the one you copied from GitHub).</p><p>VS Code will:</p><ul><li>Ask for a destination folder</li><li>Clone the project locally</li><li>Prompt you to open the project</li></ul><p>👉 Click <strong>Open</strong> once cloning is complete.</p><p>At this point, your Spring Boot project is now inside VS Code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qDltMcNn1DVL4g5_PTzHYw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bdteU4x2YjXGLd-wbVicEg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XW-MjSUK96xHVzMIKO-i_Q.jpeg" /></figure><p>🛠️ Step 4: Run Gradle Clean Build</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q3d_jXdLxBl-6YITWrM8bw.jpeg" /></figure><p>▶️ Step 6: Start Your Spring Boot Application</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T7Eo1hZ9_RKQfkm1Sph2ag.jpeg" /></figure><p>💡 What I Learned from This Setup</p><p>Switching to VS Code doesn’t mean abandoning powerful Java development, it means simplifying it.</p><p>Here’s what stands out:</p><ul><li>Faster startup compared to heavy IDEs</li><li>Clean UI with fewer distractions</li><li>Strong Git integration</li><li>Growing ecosystem for AI tools</li></ul><p>But also:</p><ul><li>You may miss some advanced refactoring features</li><li>Requires initial setup effort</li></ul><p>🧠 Final Thought</p><p>VS Code is not here to replace traditional Java IDEs , it’s offering a different way to work.</p><p>If you embrace it with the right setup, it becomes:</p><blockquote><em>A lightweight, modern, AI-ready development environment for Java</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=695709fdff36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gen AI vs AI Agents vs Agentic AI :: Simple Story of Three Smart Helpers]]></title>
            <link>https://medium.com/@manishkumar.modi/gen-ai-vs-ai-agents-vs-agentic-ai-simple-story-of-three-smart-helpers-fe773d40346d?source=rss-2d4491b2c635------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe773d40346d</guid>
            <dc:creator><![CDATA[Manishkumar Modi]]></dc:creator>
            <pubDate>Mon, 13 Apr 2026 23:35:35 GMT</pubDate>
            <atom:updated>2026-04-14T01:39:42.149Z</atom:updated>
            <content:encoded><![CDATA[<p>Ravi had just opened his small online bakery. Orders were coming in, but managing everything like messages, inventory, delivery was becoming overwhelming.</p><p>One day, his tech-savvy friend Neha introduced him to three different “helpers.”</p><blockquote><strong>The Smart Writer (Gen AI)</strong></blockquote><p>Neha first showed Ravi a chatbot.</p><p>“Ask it to write a message to your customers,” she said.</p><p>Ravi typed:<br>“Write a message for customers about delayed delivery due to rain.”</p><p>Within seconds, the chatbot replied with a polite, well-written message.</p><p>Ravi was impressed. “Wow, it writes better than me!”</p><p>Neha smiled. “This is <strong>Generative AI (Gen AI)</strong>. It <em>creates content</em> like text, images, ideas but it doesn’t <em>do</em> anything beyond that. You still have to copy, send, and act.”</p><p>👉 <strong>Simple idea:</strong><br>Gen AI = <em>A smart brain that talks and creates, but doesn’t take action on its own.</em></p><blockquote><strong>The Task Runner (AI Agent)</strong></blockquote><p>Next, Neha showed him another tool.</p><p>“Now connect this to your email and delivery system,” she said.</p><p>Ravi did. When a delay happened, the system:</p><ul><li>detected the issue</li><li>generated a message</li><li>automatically sent it to customers</li></ul><p>Ravi didn’t have to lift a finger.</p><p>“This is amazing!” he said.</p><p>Neha nodded. “This is an <strong>AI Agent</strong>. It doesn’t just generate, it <em>acts</em> based on instructions. It can use tools, send emails, update systems.”</p><p>👉 <strong>Simple idea:</strong><br>AI Agent = <em>A worker that can take actions using tools, based on what you tell it.</em></p><blockquote><strong>The Business Manager (Agentic AI)</strong></blockquote><p>Finally, Neha introduced something more advanced.</p><p>“This one,” she said, “you don’t need to micromanage.”</p><p>Ravi connected it to his bakery system.</p><p>Over the next few days, the system:</p><ul><li>noticed delivery delays happening frequently in rainy areas</li><li>suggested changing delivery partners in those zones</li><li>automatically tested a new partner</li><li>tracked customer satisfaction</li><li>optimized delivery routes</li><li>even adjusted baking schedules to avoid late dispatch</li></ul><p>Ravi was stunned. “I didn’t even ask it to do all this!”</p><p>Neha explained, “This is <strong>Agentic AI</strong>. It doesn’t just act, it <em>thinks, plans, and improves on its own</em> toward a goal.”</p><p>👉 <strong>Simple idea:</strong><br>Agentic AI = <em>A smart decision-maker that figures out goals, plans steps, and improves outcomes with minimal human input.</em></p><blockquote><strong>The Big Difference (In One Line Each)</strong></blockquote><ul><li><strong>Gen AI</strong> → <em>“Tell me what to write.”</em></li><li><strong>AI Agent</strong> → <em>“Tell me what to do.”</em></li><li><strong>Agentic AI</strong> → <em>“Tell me your goal , I’ll figure out the rest.”</em></li></ul><p><strong>Ravi’s Realization</strong></p><p>At the end of the week, Ravi told Neha:</p><ul><li>“Gen AI helped me communicate better.”</li><li>“AI Agents helped me save time.”</li><li>“Agentic AI helped me run my business smarter.”</li></ul><p>Neha laughed. “Exactly. It’s not just about intelligence anymore, it’s about <em>initiative</em>.”</p><blockquote><strong>Final Thought</strong></blockquote><p>Think of it like this:</p><ul><li>Gen AI is like a <strong>writer</strong> ✍️</li><li>AI Agent is like an <strong>assistant</strong> 🧑‍💻</li><li>Agentic AI is like a <strong>manager</strong> 🧠</li></ul><p>And the more responsibility you give, the more value you get.</p><p>That day, Ravi didn’t just upgrade his bakery.<br>He upgraded how he worked.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe773d40346d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[️ Why You Should Stop Using java.util.Date and Start Using java.time.LocalDate]]></title>
            <link>https://medium.com/@manishkumar.modi/%EF%B8%8F-why-you-should-stop-using-java-util-date-and-start-using-java-time-localdate-7743b4cd5785?source=rss-2d4491b2c635------2</link>
            <guid isPermaLink="false">https://medium.com/p/7743b4cd5785</guid>
            <dc:creator><![CDATA[Manishkumar Modi]]></dc:creator>
            <pubDate>Thu, 23 Oct 2025 02:42:18 GMT</pubDate>
            <atom:updated>2025-10-23T03:25:16.496Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve been working with Java for a while, you’ve probably come across java.util.Date and maybe even its old companion, Calendar. These classes have been part of Java since the early days, but let’s be honest: they’re <strong>confusing</strong>, <strong>mutable</strong>, and <strong>painful</strong> to work with.</p><p>When I migrated my project from Java 17 to Java 21, I decided to finally move away from Date and adopt java.time.LocalDate. And I’m glad I did. Here’s why you should too.</p><h3>🧠 1. java.time is the Modern Date-Time API</h3><p>Starting with Java 8, the new java.time package completely redefined how we handle dates and times. It&#39;s inspired by the popular Joda-Time library and designed to be <strong>clear</strong>, <strong>safe</strong>, and <strong>immutable</strong>.</p><p>No more confusion about months starting at 0 or time zones being lost in conversion — LocalDate, LocalTime, and LocalDateTime make everything explicit and easy to use.</p><h3>🧩 2. LocalDate Is Immutable and Thread-Safe</h3><p>One of the biggest advantages of LocalDate is that it&#39;s <strong>immutable</strong>. Once created, it can&#39;t be changed. That makes your code more predictable and thread-safe by default.</p><p>In contrast, java.util.Date is mutable - and in a multi-threaded environment, that can easily lead to subtle bugs.</p><h3>🕰️ 3. Cleaner and More Expressive Code</h3><p>Here’s what working with the old API looks like:</p><pre>Calendar cal = Calendar.getInstance();<br>cal.setTime(new Date());<br>cal.add(Calendar.WEEK_OF_YEAR, 1);<br>Date nextWeek = cal.getTime();</pre><p>And here’s the modern way:</p><pre>LocalDate today = LocalDate.now();<br>LocalDate nextWeek = today.plusWeeks(1);</pre><p>The difference is crystal clear — the new API is simpler, readable, and intuitive.</p><h3>🌍 4. Perfect for Business Logic</h3><p>Need a date without a time? Use LocalDate.<br>Need both date and time? Use LocalDateTime.<br>Need timezone support? Use ZonedDateTime.</p><p>The old API ( Date and Calendar) never made these distinctions clear - which led to many time zone and daylight-saving nightmares.</p><h3>🔄 5. Easy to Integrate and Convert</h3><p>Most modern frameworks like <strong>Spring Boot</strong>, <strong>Hibernate</strong>, and <strong>Jackson</strong> now support java.time natively. You can store, serialize, and format dates with zero hassle.</p><h3>✅ Final Thoughts</h3><p>If your project is still using java.util.Date, it&#39;s time to let it go. The modern java.time API is:</p><ul><li>Cleaner to read</li><li>Safer to use</li><li>Easier to test and maintain</li></ul><p>So next time you’re writing code that deals with dates, remember: <strong>Use </strong><strong>LocalDate - and leave </strong><strong>Date in the past where it belongs.</strong></p><p>📘 <strong>Interested in learning Java the right way?</strong><br>Feel free to <a href="https://www.linkedin.com/in/manishkumar-modi/"><strong>contact me</strong></a><strong> for course details</strong> and guidance tailored to real-world development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7743b4cd5785" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Why Java 21 Added getFirst() and Friends to ArrayList — Even Though They Just Call Old Methods]]></title>
            <link>https://medium.com/@manishkumar.modi/why-java-21-added-getfirst-and-friends-to-arraylist-even-though-they-just-call-old-methods-d08c9d4e4b6c?source=rss-2d4491b2c635------2</link>
            <guid isPermaLink="false">https://medium.com/p/d08c9d4e4b6c</guid>
            <dc:creator><![CDATA[Manishkumar Modi]]></dc:creator>
            <pubDate>Sat, 18 Oct 2025 02:53:27 GMT</pubDate>
            <atom:updated>2026-04-14T01:41:20.871Z</atom:updated>
            <content:encoded><![CDATA[<h2>🧭 Why Java 21 Added getFirst() and Friends to ArrayList — Even Though They Just Call Old Methods</h2><p>When I recently migrated my project from <strong>Java 17 to Java 21</strong>, I noticed something new in ArrayList:<br> methods like getFirst(), getLast(), addFirst(), addLast(), removeFirst(), and removeLast() Suddenly appeared and caught my eye.</p><p>My first reaction?<br> <strong>“Wait… why do we need these when </strong><strong>get(0) and </strong><strong>get(size()-1) already exist?”</strong></p><p>So I dug in — and what I found made a lot of sense.</p><p><a href="https://medium.com/@manishkumar.modi/why-java-21-added-getfirst-and-friends-to-arraylist-even-though-they-just-call-old-methods-d08c9d4e4b6c?sk=0bf28e48f23ce19335e1ca864e9bc4c6"><strong><em>If you are not a member — Read for free</em></strong></a></p><p>🧩 The Real Reason: The New <em>Sequenced Collections</em> API</p><p>Java 21 introduced <strong>JEP 431: Sequenced Collections</strong>, a quiet but powerful enhancement to the Java Collections Framework.</p><p>It defines a new interface:</p><pre>public interface SequencedCollection&lt;E&gt; extends Collection&lt;E&gt; {<br>    E getFirst();<br>    E getLast();<br>    void addFirst(E e);<br>    void addLast(E e);<br>    E removeFirst();<br>    E removeLast();<br>    SequencedCollection&lt;E&gt; reversed();<br>}</pre><p>The idea is simple but important to provide a <strong>consistent, unified API</strong> for <em>ordered collections</em>.</p><p>Before Java 21, each type of collection handled order differently:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AFS_HcJwUEvL8ZHVjuUoYQ.png" /></figure><p>This meant that developers couldn’t write <strong>generic code</strong> that worked across different ordered collections — List, Deque, or LinkedHashSet.</p><p>💡<strong> What Java 21 Does Differently</strong></p><p>Now, ArrayList, LinkedList, LinkedHashSet, and even LinkedHashMap Implement these new <em>Sequenced</em> interfaces.</p><p>That means you can now write code like this:</p><pre>void printEnds(SequencedCollection&lt;String&gt; seq) {<br>    System.out.println(&quot;First: &quot; + seq.getFirst());<br>    System.out.println(&quot;Last: &quot; + seq.getLast());<br>}</pre><p>and it will work seamlessly for:</p><pre>ArrayList&lt;String&gt; list = new ArrayList&lt;&gt;(List.of(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;));<br>Deque&lt;String&gt; deque = new ArrayDeque&lt;&gt;(List.of(&quot;X&quot;, &quot;Y&quot;, &quot;Z&quot;));<br><br>printEnds(list);<br>printEnds(deque);</pre><p>No more worrying about whether you’re dealing with a List or a Deque.<br> It’s all unified under one elegant abstraction.</p><p><strong>⚙️ But Internally, They Still Call Old Methods!</strong></p><p>Yes, you heard it right, and that’s completely fine.<br> If you peek into the source code of ArrayList Java 21, you’ll find:</p><pre>public E getFirst() {<br>    return get(0);<br>}<br><br>public E getLast() {<br>    return get(size() - 1);<br>}</pre><p>That’s intentional, and the goal isn’t performance — it’s <strong>API unification</strong> and <strong>semantic clarity</strong>.</p><p>Think of it like this: “These methods don’t make your code faster — they make your code cleaner, more expressive, and future-proof.”</p><p><strong>✨ Why This Matters</strong></p><p><strong>1. Readable and expressive</strong></p><p>list.getFirst() communicates intent far better than list.get(0).</p><p><strong>2. Write once, use anywhere</strong></p><p>You can now create reusable methods or libraries that operate on any sequenced collection.</p><p><strong>3. Backward-compatible evolution</strong></p><p>Older collections gain new capabilities without breaking existing code.</p><p><strong>4. Future flexibility</strong></p><p>The JDK team can now add richer features (like reversed views) consistently across all collections.</p><p><strong>🧠 A Quick Before/After</strong></p><p>Before Java 21:</p><pre>if (!list.isEmpty()) {<br>    System.out.println(&quot;First: &quot; + list.get(0));<br>    System.out.println(&quot;Last: &quot; + list.get(list.size() - 1));<br>}</pre><p>After Java 21:</p><pre>if (!list.isEmpty()) {<br>    System.out.println(&quot;First: &quot; + list.getFirst());<br>    System.out.println(&quot;Last: &quot; + list.getLast());<br>}</pre><p>Cleaner. Clearer. Consistent.</p><p><strong>🔚 Final Thoughts</strong></p><p>Java 21 didn’t add these methods just for fun.<br> They’re part of a thoughtful redesign — one that finally unifies how we handle ordered data structures across the Java Collections Framework.</p><p>It’s not about <strong>how</strong> these methods work internally — it’s about <strong>what</strong> they enable for the future.</p><p>The getFirst() and getLast() revolution is small, silent, but meaningful — making Java collections a little more modern, readable, and developer-friendly.</p><p><strong>If you’ve migrated from Java 17 to 21 like me, give these new methods a try.</strong><br> You might just find your code not only cleaner, but also ready for whatever comes next in Java’s evolution. ☕✨</p><p>📘 <strong>Interested in learning Core Java the right way?</strong><br>Feel free to <a href="https://www.linkedin.com/in/manishkumar-modi/"><strong>contact me</strong></a><strong> for course details</strong> and guidance tailored to real-world development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d08c9d4e4b6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why India Resists Opening Its Dairy Market to the U.S.]]></title>
            <link>https://medium.com/@manishkumar.modi/why-india-resists-opening-its-dairy-market-to-the-u-s-3c98cbf09fb2?source=rss-2d4491b2c635------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c98cbf09fb2</guid>
            <category><![CDATA[trade]]></category>
            <dc:creator><![CDATA[Manishkumar Modi]]></dc:creator>
            <pubDate>Mon, 01 Sep 2025 03:39:49 GMT</pubDate>
            <atom:updated>2025-09-01T10:53:46.695Z</atom:updated>
            <content:encoded><![CDATA[<h2>U.S.A Trade Deal vs Farmers, Why India Resists Opening Its Dairy Market to the U.S.A</h2><p>When Prime Minister Narendra Modi declared that India will “never compromise on the interests of farmers, fishermen, and dairy farmers,” it caught my attention.</p><p>At first, I wondered: Why this strong stance on dairy? After all, India is the world’s largest producer of milk. Our villages thrive on dairy, from morning chai to religious offerings. And usually, U.S. products are more expensive than Indian ones. So how could American milk or cheese possibly hurt Indian farmers, even if a free trade deal is signed?</p><p>Curious, I dug deeper. And the answers surprised me.</p><p><strong>America’s Advantage: Subsidies and Scale</strong></p><p>In the U.S., dairy farming is industrial-scale. One farm can have thousands of cows, milked by machines, fed on subsidized corn and soy, and supported by government programs. The U.S. government provides direct subsidies, price supports, and insurance schemes that keep farmers afloat, even when markets are weak.</p><p>This allows American dairy exporters to sell abroad at artificially low prices. In many cases, they offload surplus products like skimmed milk powder, whey protein, and cheese at rates small farmers in India simply cannot match.</p><p><strong>India’s Dairy: Small and Fragmented</strong></p><p>Back home, dairy is a smallholder enterprise. The average Indian farmer owns 2 – 3 cows or buffaloes, depends on family labor, and faces high feed and veterinary costs. Productivity is lower than in the U.S., and costs per litre hover around ₹25 – 28 for small farmers.</p><p>While cooperatives like Amul have created a strong model, Indian dairy is still fragile. Prices only need to fall a little for millions of families to lose their thin margins.</p><p><strong>The Twist: Why U.S. Exports Look Cheaper</strong></p><p>Here’s the part that puzzled me the most: fresh milk in U.S. supermarkets is 2 – 3 times costlier than in India. A litre of milk in New York can easily cost ₹85 – 100, compared to ₹35 – 45</p><p>here.</p><p><strong>So how can American products undercut Indian farmers?</strong></p><p>The key is: the U.S. doesn’t export fresh milk. It exports bulk-processed products like milk powder and whey. Thanks to subsidies and industrial efficiency, the farm-gate price (what U.S. farmers actually receive) can be much lower – often just ₹30 – 33/litre equivalent. Once converted into powder, these products can land in India at about ₹22 – 25/litre equivalent if tariffs are reduced.</p><p>That’s cheaper than what Indian farmers spend to produce milk.</p><p><strong>What a Trade Deal Could Mean</strong></p><p>Currently, India protects its dairy sector with import tariffs of 30% – 60%. This is the shield keeping U.S. dairy from flooding the market. But under free trade talks, the U.S. has been pushing India to open its dairy sector.</p><p>A State Bank of India report warns that liberalizing dairy imports could cause Indian farmers to lose ₹1.03 lakh crore annually. Domestic milk prices could fall by 15% or more, devastating rural livelihoods.</p><p><strong>More Than Economics: A Rural Safety Net</strong></p><p>The dairy sector isn’t just another industry. It is a social stabilizer:</p><p>•	It gives rural families a steady income, especially women.</p><p>•	It supports households during crop failures.</p><p>•	It contributes significantly to food security.</p><p>Opening the floodgates to subsidized U.S. imports could weaken this safety net.</p><p><strong>The Bottom Line</strong></p><p>When I started, I thought U.S. dairy would be too expensive to matter. But after digging into subsidies, surplus dumping, and tariff protections, I understood why India is cautious.</p><p>What looks like an opportunity for cheaper imports on paper is, in reality, a threat to millions of small farmers.</p><p>So when Modi says India will never compromise on farmers’ interests, dairy is at the heart of that promise. For India, protecting rural livelihoods comes before any flashy trade deal.</p><p>⸻</p><p>👉 Support your country, and remember: protecting farmers – the backbone of the Indian economy – is not just important, it is essential.</p><p>🙏 A big thanks to ChatGPT for helping me understand this matter and these stats.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c98cbf09fb2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Understanding equals() and hashCode(): A Costly Mistake That Taught Me Java’s Object Contract]]></title>
            <link>https://medium.com/@manishkumar.modi/understanding-equals-and-hashcode-a-costly-mistake-that-taught-me-javas-object-contract-52bfdb9f06b4?source=rss-2d4491b2c635------2</link>
            <guid isPermaLink="false">https://medium.com/p/52bfdb9f06b4</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[hashing]]></category>
            <category><![CDATA[core-java]]></category>
            <dc:creator><![CDATA[Manishkumar Modi]]></dc:creator>
            <pubDate>Sun, 03 Aug 2025 19:47:58 GMT</pubDate>
            <atom:updated>2025-09-15T13:06:13.944Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qkUG8uu9S9d9rmUKAR5mlQ.png" /></figure><p><a href="https://medium.com/@manishkumar.modi/understanding-equals-and-hashcode-a-costly-mistake-that-taught-me-javas-object-contract-52bfdb9f06b4?source=friends_link&amp;sk=328897d92067053255bdb24d8c622b44"><strong><em>If you are not a member — Read for free</em></strong></a></p><p>Introduction: A Bug That Didn’t Make Sense</p><p>When I had around 4 years of experience, I encountered a bug that made me question everything I knew about Java collections.</p><p>We were storing User objects in a HashSet, and to my surprise, it started allowing <strong>duplicates</strong>. Two users with the same values for email and name were both making it into the set.</p><p>I remember thinking:<br><strong>“Aren’t sets supposed to prevent duplicates? What’s going on?”</strong></p><p>That moment taught me one of the most important lessons in Core Java — a lesson that even experienced developers sometimes forget:<br> 👉 <strong>You must override both </strong><strong>equals() and </strong><strong>hashCode() properly if you care about logical equality.</strong></p><p>🔍<strong> The Setup: My Faulty Class</strong></p><p>Here’s what our class looked like:</p><pre>public class User {<br>    private String email;<br>    private String name;<br><br>    public User(String email, String name) {<br>        this.email = email;<br>        this.name = name;<br>    }<br><br>    // No equals() and hashCode() methods!<br>}</pre><p>And the logic we had was:</p><pre>Set&lt;User&gt; users = new HashSet&lt;&gt;();<br><br>users.add(new User(&quot;abc@example.com&quot;, &quot;Abc&quot;));<br>users.add(new User(&quot;abc@example.com&quot;, &quot;Abc&quot;));  // Expected to be ignored<br><br>System.out.println(users.size());  // ❌ Output: 2</pre><p>Even though the two User objects looked the same, the HashSet thought otherwise.</p><h3>🤯 Why This Happened</h3><p>Here’s what I later learned (and wish I had known earlier):</p><ul><li>HashSet uses <strong>hashCode()</strong> to determine the bucket.</li><li>Then it uses <strong>equals()</strong> to determine actual equality.</li><li>If you <strong>don’t override</strong> these methods, Java uses the default implementation from Object:</li><li>equals() compares <strong>memory references</strong>.</li><li>hashCode() is also derived from the memory location.</li></ul><p>In our case, we had two different objects (different memory addresses), so:</p><ul><li>They had different hashCode() values.</li><li>equals() ignored or considered returned false.</li></ul><p>As far as Java was concerned, they were totally unrelated objects.</p><p>✅ The Fix: Override Both Methods</p><p>We updated the class like this:</p><pre>@Override<br>public boolean equals(Object o) {<br>    if (this == o) return true;<br>    if (o == null || getClass() != o.getClass()) return false;<br>    User user = (User) o;<br>    return Objects.equals(email, user.email);<br>}<br><br>@Override<br>public int hashCode() {<br>    return Objects.hash(email);<br>}</pre><p>Now, when we ran:</p><pre>Set&lt;User&gt; users = new HashSet&lt;&gt;();<br>users.add(new User(&quot;abc@example.com&quot;, &quot;abc&quot;));<br>users.add(new User(&quot;abc@example.com&quot;, &quot;abc&quot;));<br>System.out.println(users.size()); // ✅ Output: 1</pre><p>It worked exactly as expected.</p><p>🧠 The Object Contract You Should Never Break</p><p>Java has a <strong>core contract</strong> between equals() and hashCode():</p><ul><li>If two objects are <strong>equal according to </strong><strong>equals()</strong>, they <strong>must return the same </strong><strong>hashCode()</strong>.</li></ul><p>But the reverse is <strong>not</strong> required:</p><ul><li>Two objects with the same hashCode() may still not be<em> equal</em></li></ul><p>Violating this contract causes erratic behaviour in collections like HashSet, HashMap, and Hashtable.</p><p>🔧<strong> Real-World Impact</strong></p><p>Here’s how this small mistake caused bigger issues:</p><ul><li>We ended up with <strong>duplicate entries</strong> in our cache and persisted collections.</li><li>Our UI dropdowns listed the same user multiple times.</li><li>Logs and audit trails showed inconsistencies.</li><li>Debugging the issue took us far longer than it should have.</li></ul><p><strong>💡 Lessons I Learned</strong></p><p>Here’s what I took away from this:</p><ul><li>Always override <strong>both</strong> equals() and hashCode()—never just one.</li><li>Use <strong>only immutable fields</strong> like id or email for comparison.</li><li>Let your <strong>IDE generate</strong> these methods to avoid subtle bugs.</li><li>For modern projects, use <strong>Lombok </strong><strong>@EqualsAndHashCode</strong> to avoid boilerplate (but understand how it works).</li></ul><p><strong>📘 Quick Cheatsheet</strong></p><p><strong>✅ When to Override:</strong></p><ul><li>When objects will be stored in collections like HashSet, HashMap, TreeSet, etc.</li><li>When <strong>logical equality</strong> matters (not just identity).</li></ul><p><strong>🚫 What to Avoid:</strong></p><ul><li>Using <strong>mutable fields</strong> in equals() or hashCode().</li><li>Ignoring hashCode() when equals() is overridden.</li><li>Comparing with fields that may change over time (like name, status, etc.).</li></ul><p><strong>🔚 Conclusion</strong></p><p>That bug from my <strong>4th year as a developer</strong> turned out to be one of the most valuable Java lessons I’ve ever learned.</p><p>It taught me that in Java, writing code isn’t just about syntax — it’s about <strong>respecting contracts</strong> and understanding how the language behaves under the hood.</p><p>So the next time something strange happens in your HashSet or HashMap, check your equals() and hashCode() first.</p><p>They might be the silent troublemakers you’ve been ignoring.</p><p><strong>Every time I take technical interviews</strong>, I make sure to ask candidates about:</p><ul><li>The purpose and implementation of equals() and hashCode(), and</li><li>How Java’s <strong>hashing mechanism</strong> works internally — because understanding this isn’t just academic. It’s critical to write bug-free, production-level Java code.</li></ul><p>If you found this content helpful, feel free to show your support with 👏 claps! 😊 Your encouragement keeps me motivated to share my experiences.</p><p>💬 <em>Have you faced a similar issue in your early years? Drop a comment — I’d love to hear your story.</em></p><p>📘 <strong>Interested in learning Core Java the right way?</strong><br> Feel free to <a href="https://www.linkedin.com/in/manishkumar-modi/"><strong>contact me</strong></a><strong> for course details</strong> and guidance tailored to real-world development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52bfdb9f06b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[️ From @Scheduled to ScheduledTaskConfigurer: My Journey Through Thread Pool Chaos in Spring Boot]]></title>
            <link>https://medium.com/@manishkumar.modi/%EF%B8%8F-from-scheduled-to-scheduledtaskconfigurer-our-journey-through-thread-pool-chaos-in-6aa18704be05?source=rss-2d4491b2c635------2</link>
            <guid isPermaLink="false">https://medium.com/p/6aa18704be05</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[scheduling]]></category>
            <dc:creator><![CDATA[Manishkumar Modi]]></dc:creator>
            <pubDate>Sat, 05 Jul 2025 22:05:45 GMT</pubDate>
            <atom:updated>2025-09-15T13:00:18.920Z</atom:updated>
            <content:encoded><![CDATA[<p>In every system that relies on time-based operations, task scheduling is a natural part of the architecture.</p><p>In our case, we have a Spring Boot microservice that retrieves data from an upstream application and stores it in CSV files. Sounds simple, right?</p><p>However, as with most production systems, what started as a neat and tidy solution quickly evolved into a web of concurrency problems, thread starvation, and CPU overload. In this article, I’ll walk you through <strong>our journey from </strong><strong>@Scheduled to </strong><strong>@Async, and finally to </strong><strong>ScheduledTaskConfigurer</strong>—and what we learned along the way.</p><p>🚀 The Beginning: @Scheduled – Easy and Effective</p><p>When we began building the service, we used Spring Boot’s @Scheduled annotation to schedule a method that runs every few minutes:</p><pre>@Scheduled(fixedRate = 300000) // every 5 minutes<br>public void pullAndStoreData() {<br>    // Fetch data from upstream<br>    // Process it<br>    // Write to CSV<br>}</pre><p>This was clean and simple. Spring took care of the scheduling, and it worked great in development and early production traffic. But this approach comes with a catch…</p><p>❗ The Hidden Limitation</p><p>By default, all @Scheduled tasks run on <strong>a single-threaded executor</strong>. That means only one task runs at a time. If the scheduled method takes 2–3 minutes to execute, and another method is also scheduled, the second one <strong>has to wait</strong>, even if it was scheduled to run earlier.</p><p>At first, this wasn’t a problem. But as upstream data grew and our processing time increased, we saw <strong>delays</strong> and <strong>overlapping tasks being skipped</strong>. It was time to optimize.</p><p>⚙️ The Next Step: @Async – Let&#39;s Go Parallel</p><p>To allow parallel execution, we thought: why not just make the scheduled method asynchronous?</p><pre>@Async<br>@Scheduled(fixedRate = 300000)<br>public void pullAndStoreData() {<br>    // Same logic<br>}</pre><p>We added @EnableAsync and defined a custom TaskExecutor to control the thread pool size:</p><pre>@Bean<br>public Executor taskExecutor() {<br>    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();<br>    executor.setCorePoolSize(5);<br>    executor.setMaxPoolSize(10);<br>    executor.setQueueCapacity(20);<br>    executor.setThreadNamePrefix(&quot;AsyncExecutor-&quot;);<br>    executor.initialize();<br>    return executor;<br>}</pre><p>✅ The Good</p><ul><li>Now, multiple scheduled tasks could run <strong>in parallel</strong>.</li><li>The scheduler was free to fire again while the actual job ran in the async thread.</li></ul><p>❌ The Bad (and Ugly)</p><p>As traffic continued to increase, each scheduled task started taking longer, and our fixedRate kept launching new tasks <strong>every 5 minutes, regardless of whether the previous one had finished</strong>.</p><p>Before long:</p><ul><li><strong>The async thread pool was exhausted.</strong></li><li>New tasks were <strong>rejected</strong>.</li><li>The CPU started spiking.</li><li>ExceptionsRejectedExecutionException began appearing in logs.</li></ul><p>We had traded the blocking problem for a <strong>concurrency bomb</strong>.</p><p>🧯The Solution: Enter ScheduledTaskConfigurer</p><p>We needed <strong>better control</strong> over both the <strong>scheduling</strong> and <strong>execution</strong> sides of our tasks. That’s when we moved to ScheduledTaskConfigurer—Spring&#39;s way of letting you define your scheduler with a bounded thread pool.</p><p>🔧 Here’s what we did:</p><pre>@Configuration<br>@EnableScheduling<br>public class SchedulingConfig implements SchedulingConfigurer {<br><br>    @Override<br>    public void configureTasks(ScheduledTaskRegistrar registrar) {<br>        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();<br>        scheduler.setPoolSize(5); // Fixed, safe limit<br>        scheduler.setThreadNamePrefix(&quot;CustomScheduler-&quot;);<br>        scheduler.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // Fallback<br>        scheduler.initialize();<br><br>        registrar.setTaskScheduler(scheduler);<br>    }<br>}</pre><p>Now, all @Scheduled Methods are scheduled and executed <strong>using this scheduler</strong>. No more separation between scheduling and execution logic. It’s <strong>one thread pool</strong>, fully under our control.</p><p>✅ Benefits We Gained</p><ul><li><strong>Bounded concurrency</strong>: Only up to 5 threads are active at a time.</li><li><strong>No overlap issues</strong>: Tasks wait in the queue if the pool is full.</li><li><strong>Cleaner architecture</strong>: No mix of schedulers and async executors.</li><li><strong>Better monitoring</strong>: Easier to trace and log thread activity.</li><li><strong>Fail-safe</strong>: Rejected tasks are handled predictably.</li></ul><p>🧠 Key Takeaways</p><p><strong>1. Avoid </strong><strong>@Async with </strong><strong>@Scheduled for long-running or high-frequency tasks</strong>.</p><ul><li>It looks easy but lacks control and can lead to thread pool exhaustion.</li></ul><p><strong>2. Use </strong><strong>ScheduledTaskConfigurer When tasks are non-trivial</strong>.</p><ul><li>It gives you real power: parallelism + predictability.</li></ul><p><strong>3. Always configure thread pools explicitly in production systems</strong>.</p><ul><li>Default settings are never enough.</li></ul><p>🏁 Final Thoughts</p><p>Scheduling in Spring Boot is powerful, but you must choose the right tool for the job. @Scheduled It&#39;s great for small, simple jobs. Add @Async, and you get parallelism—but without guardrails.</p><p>When your system starts scaling and task duration increases, <strong>go with </strong><strong>ScheduledTaskConfigurer</strong>. It saved us from drowning in concurrent tasks and made our service stable under heavy load.</p><p>Thanks for reading! I hope my story helps you make smarter decisions when designing scheduled systems in Spring Boot.</p><p>👉 If you’ve faced similar challenges or have tips, drop them in the comments — let’s learn from each other!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6aa18704be05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Change Log Level at Runtime in Spring Boot Without Restarting the Application]]></title>
            <link>https://medium.com/@manishkumar.modi/change-log-level-at-runtime-in-spring-boot-without-restarting-the-application-e5d3263679cb?source=rss-2d4491b2c635------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5d3263679cb</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[coding-standards-java]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[production]]></category>
            <dc:creator><![CDATA[Manishkumar Modi]]></dc:creator>
            <pubDate>Sat, 14 Jun 2025 18:29:51 GMT</pubDate>
            <atom:updated>2025-09-15T13:06:33.025Z</atom:updated>
            <content:encoded><![CDATA[<p>Logging is your best friend during development and troubleshooting in production. But have you ever been in a situation where your app is misbehaving, and you wished you could turn on DEBUG logs temporarily without restarting the Spring Boot application?</p><p>Good news: Spring Boot provides a way to dynamically change log levels at runtime, thanks to its integration with the Spring Boot Actuator.</p><p>Let’s walk through how to set it up, examples, real-world challenges, and how this feature made our lives easier in production.</p><p>🚧 The Challenge: Debugging in Production Without Logs</p><p>Not long ago, I was supporting a Spring Boot application in production. Everything looked fine on the surface – no exceptions, no alerts – but users were complaining that some notification emails were not being sent.</p><p>The problem? Logs at INFO level didn’t give enough detail. We needed to see what was happening inside the service methods, especially around the email notification flow.</p><p>Here were the key challenges I faced:</p><p>❗1. No DEBUG logs in production</p><p>We had disabled DEBUG logs in production to reduce log volume and costs. That meant no trace of request processing, database payloads, or internal method calls.</p><p>🚫 2. Restarting was not an option</p><p>Restarting the service with DEBUG logs enabled was risky and time-consuming, especially during business hours.</p><p>🔍 3. Incomplete visibility through monitoring tools</p><p>We had good observability on metrics and errors, but not on what caused the missing notifications. There were no exceptions – just silent failures.</p><p>✅ Solution: Dynamic Log Level with Spring Boot Actuator</p><p>By enabling the /actuator/loggers endpoint, I was able to dynamically change the log level of just the relevant package (com.example.notification) to DEBUG – without restarting the app.</p><pre>curl -X POST http://&lt;host&gt;:8080/actuator/loggers/com.example.notification \<br>-H &quot;Content-Type: application/json&quot; \<br>-d ‘{&quot;configuredLevel&quot;: &quot;DEBUG&quot;}’</pre><p>🧠 What I Found</p><p>After enabling debug logs:</p><p>•	I saw that the email service was receiving the correct request.</p><p>•	However, due to a silent validation check, the email ID was marked as invalid.</p><p>•	That log line was only available at the DEBUG level.</p><p>We quickly fixed the validation rule and restored the proper flow – without any downtime.</p><p>🛠️ Step-by-Step: How to Enable Dynamic Logging</p><p>1. Add Actuator to Your Project</p><p>Maven:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>Gradle:</p><pre>implementation &#39;org.springframework.boot:spring-boot-starter-actuator&#39;</pre><p>2. Enable the Loggers Endpoint</p><p>In application.properties:</p><pre>management.endpoints.web.exposure.include=loggers</pre><p>Or YAML:</p><pre>management:<br>  endpoints:<br>    web:<br>      exposure:<br>        include: loggers</pre><p>3. Change Log Level at Runtime</p><pre>curl -X POST http://localhost:8080/actuator/loggers/com.example.service \<br>-H &quot;Content-Type: application/json&quot; \<br>-d &#39;{&quot;configuredLevel&quot;: &quot;DEBUG&quot;}&#39;</pre><p>And revert when done:</p><pre>-d &#39;{&quot;configuredLevel&quot;: &quot;INFO&quot;}&#39;</pre><p>🔐 Secure the Actuator Endpoints</p><p>Always protect sensitive actuator endpoints using Spring Security or API gateway authentication. Expose only what’s necessary:</p><pre>management.endpoints.web.exposure.include=loggers<br>management.endpoint.loggers.enabled=true</pre><p>✅ Key Takeaways</p><ul><li>Dynamically changing the log level helped resolve a production issue <strong>without requiring redeployment</strong>.</li><li>It gave instant visibility into what was going wrong inside the app.</li><li>It’s one of the most <strong>underutilized but powerful features</strong> for Java microservices in production.</li></ul><p>🧘‍♂️ Final Thoughts</p><p>In production, time and uptime are money. The ability to <strong>change log levels dynamically</strong> not only saved us from a risky deployment but also helped us find and fix the issue in minutes.</p><p>If you’re running Spring Boot in production, don’t wait for a crisis — <strong>enable this feature today</strong> and thank yourself later.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5d3263679cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Taming the Logs: How Mapped Diagnostic Context (MDC) Made REST API Debugging in Spring Boot…]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">&#x1F4D6; Introduction: The Logging Mess</p><p class="medium-feed-link"><a href="https://medium.com/@manishkumar.modi/taming-the-logs-how-mapped-diagnostic-context-mdc-made-rest-api-debugging-in-spring-boot-cd2a6d23c140?source=rss-2d4491b2c635------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@manishkumar.modi/taming-the-logs-how-mapped-diagnostic-context-mdc-made-rest-api-debugging-in-spring-boot-cd2a6d23c140?source=rss-2d4491b2c635------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd2a6d23c140</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[threadlocal]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Manishkumar Modi]]></dc:creator>
            <pubDate>Sat, 14 Jun 2025 03:00:42 GMT</pubDate>
            <atom:updated>2025-07-24T22:13:36.257Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Stop Catching Everything: Smarter Exception Handling in Java Spring Boot with @ControllerAdvice]]></title>
            <link>https://medium.com/@manishkumar.modi/stop-catching-everything-smarter-exception-handling-in-java-spring-boot-with-controlleradvice-2eb20794e62a?source=rss-2d4491b2c635------2</link>
            <guid isPermaLink="false">https://medium.com/p/2eb20794e62a</guid>
            <category><![CDATA[java-exception-handling]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Manishkumar Modi]]></dc:creator>
            <pubDate>Sat, 31 May 2025 03:41:52 GMT</pubDate>
            <atom:updated>2025-09-15T13:06:47.727Z</atom:updated>
            <content:encoded><![CDATA[<p>In this one, I’m diving into one of my favourite and most debated topics with colleagues: ‘Exception Handling’ in Java Spring Boot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*sIeBYJGRHFjbBdYKwKHQCQ.jpeg" /><figcaption>Photo Credit: Copied from <a href="https://www.atatus.com/blog/">Atatus Blog — For DevOps Engineers, Web App Developers and Server Admins.</a></figcaption></figure><p>When I started building web applications with Java and Spring Boot, exception handling felt like a patchwork of try-catch blocks, scattered logs, and Http 500 Internal Server Error(My colleauges favourite :P)errors that confused end users.</p><p>Sound familiar?</p><p>Exception handling is one of the most overlooked yet critical parts of building a reliable backend. Done poorly, it leads to unreadable code and a poor user experience. Done right, it becomes your app’s safety net and a debugging superpower.</p><p>So, how are people doing it today — and how can we do better?</p><p>🧱 <strong>The Problem with Traditional Exception Handling</strong></p><p>Many Java developers still rely on:</p><pre>try {<br>    // some risky logic<br>} catch (Exception e) {<br>    e.printStackTrace();<br>    throw new RuntimeException(&quot;Something went wrong&quot;);<br>}</pre><p>Or worse:</p><pre>catch (Exception e) {<br>    // swallow the exception<br>}</pre><p>These approaches lead to:</p><ul><li>Generic, unhelpful error messages.</li><li>Duplicated try-catch logic across layers.</li><li>Missed business logic exceptions that deserve custom messages and status codes.</li></ul><p>✅ <strong>The Spring Boot Way: Using </strong><strong>@ControllerAdvice</strong></p><p>Enter @ControllerAdvice, a powerful way to handle exceptions globally in your Spring Boot REST API.</p><p>It lets you centralize all your exception handling, respond with meaningful error messages, and return the correct HTTP status codes. Cleaner, DRY-er, and much easier to maintain.</p><p>🛠️ <strong>How It Works (Code Example)</strong></p><pre>@RestController<br>@RequestMapping(&quot;/users&quot;)<br>public class UserController {<br><br>    @GetMapping(&quot;/{id}&quot;)<br>    public User getUser(@PathVariable Long id) {<br>        return userService.findById(id)<br>            .orElseThrow(() -&gt; new UserNotFoundException(&quot;User not found with id: &quot; + id));<br>    }<br>}</pre><p>Instead of handling the exception in the controller, let&#39;s @ControllerAdvice do it:</p><pre>@ControllerAdvice<br>public class GlobalExceptionHandler {<br><br>    @ExceptionHandler(UserNotFoundException.class)<br>    public ResponseEntity&lt;ErrorResponse&gt; handleUserNotFound(UserNotFoundException ex) {<br>        ErrorResponse error = new ErrorResponse(<br>            HttpStatus.NOT_FOUND.value(),<br>            ex.getMessage(),<br>            LocalDateTime.now()<br>        );<br>        return new ResponseEntity&lt;&gt;(error, HttpStatus.NOT_FOUND);<br>    }<br><br>    @ExceptionHandler(Exception.class)<br>    public ResponseEntity&lt;ErrorResponse&gt; handleGenericException(Exception ex) {<br>        ErrorResponse error = new ErrorResponse(<br>            HttpStatus.INTERNAL_SERVER_ERROR.value(),<br>            &quot;An unexpected error occurred&quot;,<br>            LocalDateTime.now()<br>        );<br>        return new ResponseEntity&lt;&gt;(error, HttpStatus.INTERNAL_SERVER_ERROR);<br>    }<br>}</pre><p>And your ErrorResponse class:</p><pre>public class ErrorResponse {<br>    private int status;<br>    private String message;<br>    private LocalDateTime timestamp;<br><br>    // constructors, getters, setters or use lombok to avoid boilerplate code<br>}</pre><h3>💡 Best Practices</h3><ul><li>Create custom exception classes (e.g., UserNotFoundException, InvalidRequestException Instead of throwing RuntimeException.</li><li>Always return appropriate HTTP status codes (404, 400, 500, etc.).</li><li>Log exceptions in the @ControllerAdvice, not in the controller.</li><li>Keep your error responses consistent and user-friendly.</li></ul><h3>🚀 Why It Matters</h3><p>Using @ControllerAdvice It isn’t just about writing cleaner code—it’s about:</p><ul><li>Making APIs more intuitive for frontend and mobile developers.</li><li>Reducing debugging time in production.</li><li>Building applications that scale better and fail more gracefully.</li></ul><p><strong>In short, a good exception handler doesn’t just react to failure — it communicates it clearly and professionally.</strong></p><p>So if you’re still catching all exceptions or repeating error logic in every controller, consider embracing @ControllerAdvice it in your next Spring Boot project. Your future self (and your team) will thank you.</p><p>These approaches lead to:</p><ul><li>Generic, unhelpful error messages.</li><li>Duplicated try-catch logic across layers.</li><li>Missed business logic exceptions that deserve custom messages and status codes.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2eb20794e62a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>