<?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 Aindrila Polley on Medium]]></title>
        <description><![CDATA[Stories by Aindrila Polley on Medium]]></description>
        <link>https://medium.com/@aindrilapolley12?source=rss-b5d1e1be876e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*OnsKTxF_4YW9VtHgMyfPYA.png</url>
            <title>Stories by Aindrila Polley on Medium</title>
            <link>https://medium.com/@aindrilapolley12?source=rss-b5d1e1be876e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 13:04:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aindrilapolley12/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[☕ Java Nuggets: Don’t Hardwire. Inject.]]></title>
            <link>https://medium.com/@aindrilapolley12/java-nuggets-dont-hardwire-inject-9ac4834f94b5?source=rss-b5d1e1be876e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ac4834f94b5</guid>
            <category><![CDATA[java-nuggets]]></category>
            <dc:creator><![CDATA[Aindrila Polley]]></dc:creator>
            <pubDate>Sun, 27 Jul 2025 12:59:03 GMT</pubDate>
            <atom:updated>2025-07-27T12:59:03.587Z</atom:updated>
            <content:encoded><![CDATA[<p>There was a time you used to create everything inside the class — new FileReader(...), new SomeService(), new Whatever(). It felt like you were in control.</p><p>But it was a trap.<br> And <strong>Dependency Injection</strong> pulled you out.</p><h3>💥 What’s the real problem?</h3><p>When you hardcode resources inside your class, here’s what happens:</p><ul><li>You make <strong>decisions too early</strong> (like <em>which</em> implementation to use).</li><li>You tie your hands behind your back when you want to test.</li><li>You create classes that look “simple” but are <strong>secretly inflexible</strong>.</li></ul><p>Ever tried unit testing a class that creates its own database connection?<br> Yeah. That.</p><h3>👻 The Static Utility Illusion</h3><p>Static utility classes look clean — until they don’t.</p><p>They’re great for stateless, pure functions.<br> But the moment they start touching state, environment, configs, or external systems — they become <strong>invisible monsters</strong>:</p><ul><li>Impossible to mock</li><li>Tied to global assumptions</li><li>Zero flexibility</li></ul><p>Think you’re saving time?<br> You’re actually <strong>locking down the future</strong>.</p><h3>🧩 Singleton ≠ Simplicity</h3><p>Singletons often show up next. One instance to rule them all.<br> But here’s the catch: you still have to <strong>reach into the class</strong> to get it.</p><p>That’s just hardcoding with extra steps.</p><p>Plus, singletons are basically <strong>global state</strong>, and global state is where bugs and night sweats are born.</p><h3>🌱 Enter Dependency Injection</h3><p>DI flips the script.<br> Your class says: “Hey, I need this thing. You give it to me.”</p><p>And the outside world says: “Cool. Here’s the implementation you need.”</p><p>Result?</p><ul><li>Your class doesn’t care where the dependency comes from.</li><li>You can swap implementations on the fly.</li><li>You can mock, test, replace, extend — without touching the core logic.</li></ul><p>It’s clean. It’s elegant. It’s how grown-up Java code communicates.</p><h3>🔍 Still not sure when to use DI?</h3><p>Ask yourself:</p><blockquote><em>“If I moved this class to another project, would it break unless I copied 3 other things with it?”</em></blockquote><p>If the answer is yes, you’re too coupled.<br> Inject instead.</p><h3>✅ Java Nugget Takeaway</h3><p>Avoid:</p><pre>private final SomeService service = new SomeService();</pre><p>Prefer:</p><pre>private final SomeService service;<br><br>public MyClass(SomeService service) {<br>    this.service = service;<br>}</pre><p>Bonus: now you can test MyClass by passing a mock. No frameworks, no magic—just clarity.</p><h3>🧠 Final Thought</h3><p>Code is like Lego.<br> The more you glue pieces together, the less you can build.</p><p>Dependency Injection keeps your blocks modular, your code clean, and your future open.</p><p>Inject. Don’t glue.</p><h3>📌 Java Nuggets Recap</h3><ul><li>Nugget #1: <em>Prefer Static Factory Methods</em></li><li>Nugget #2: <em>Use Builders for Many Parameters</em></li><li>Nugget #3: <em>Enforce Singleton with Private Constructor or Enum</em></li><li>Nugget #4: <em>Make Utility Classes Noninstantiable</em></li><li>✅ Nugget #5: <em>Inject, Don’t Hardwire — Even Over Static and Singleton Patterns</em></li></ul><blockquote>“Global access is easy. But so is breaking everything when one thing changes.”</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ac4834f94b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Java Nuggets #4: Enforce Noninstantiability with a Private Constructor]]></title>
            <link>https://medium.com/@aindrilapolley12/java-nuggets-4-enforce-noninstantiability-with-a-private-constructor-ec5bc2f7491d?source=rss-b5d1e1be876e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec5bc2f7491d</guid>
            <category><![CDATA[java-nuggets]]></category>
            <dc:creator><![CDATA[Aindrila Polley]]></dc:creator>
            <pubDate>Sun, 27 Jul 2025 11:30:25 GMT</pubDate>
            <atom:updated>2025-07-27T11:30:25.130Z</atom:updated>
            <content:encoded><![CDATA[<p>Some classes in Java aren’t meant to be instantiated.</p><p>Think utility classes like java.lang.Math, java.util.Collections, or your own helper classes filled with static methods.</p><p>So how do you prevent someone from doing this?</p><pre>new Math(); // 🤦 why??</pre><p>Welcome to <strong>Java Nuggets #4</strong>, where we talk about enforcing <strong>noninstantiability</strong> using one simple trick: a <strong>private constructor</strong>.</p><h3>🔧 The Problem</h3><p>Let’s say you write a utility class:</p><pre>public class StringUtils {<br>    public static boolean isEmpty(String s) {<br>        return s == null || s.isEmpty();<br>    }<br>}</pre><p>Looks fine, right? But this compiles:</p><pre>StringUtils utils = new StringUtils(); // ❌ Bad idea</pre><p>The class wasn’t designed for object creation, but Java allows it by default unless you explicitly stop it.</p><h3>✅ The Fix: Private Constructor</h3><pre>public class StringUtils {<br>    private StringUtils() {<br>        throw new AssertionError(&quot;Cannot instantiate utility class&quot;);<br>    }<br><br>    public static boolean isEmpty(String s) {<br>        return s == null || s.isEmpty();<br>    }<br>}</pre><h4>🧪 Now:</h4><pre>StringUtils utils = new StringUtils(); // ❌ Compilation OK, but runtime error</pre><h4>💥 Output:</h4><pre>Exception in thread &quot;main&quot; java.lang.AssertionError: Cannot instantiate utility class</pre><p>Even better: IDEs and tools will highlight the constructor as <strong>inaccessible</strong>, discouraging misuse.</p><h3>💡 Why Throw AssertionError?</h3><ul><li>It’s a <strong>rarely used error</strong> that clearly signals misuse.</li><li>It helps if someone uses <strong>reflection</strong> to bypass access checks.</li><li>It documents intent — this class is <strong>never meant to be instantiated</strong>.</li></ul><h3>🧠 Where This Pattern Applies</h3><ul><li>Utility/helper classes with only static methods</li><li>Constant holder classes (Constants, AppConfig)</li><li>Static factory providers</li><li>Global validators or converters</li></ul><h3>📚 Real JDK Examples</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x4Hf85KYZ8nMn-Pp5mIYrA.png" /></figure><p>All of these use <strong>private constructors</strong> to prevent instantiation.</p><h3>🛡️ Additional Best Practices</h3><ul><li>✅ Mark the class as final to prevent subclassing.</li><li>✅ Document clearly: <em>“This class is not meant to be instantiated.”</em></li><li>❌ Avoid making the constructor protected — it&#39;s still visible to subclasses.</li></ul><h3>🧩 TL;DR</h3><ul><li>Don’t want your class to be instantiated? Use a <strong>private constructor</strong>.</li><li>Throw an <strong>AssertionError</strong> for added safety.</li><li>Use for <strong>utility classes</strong>, <strong>constants</strong>, and <strong>static-only APIs</strong>.</li></ul><h3>📌 Java Nuggets Recap</h3><ul><li>Nugget #1: <em>Prefer Static Factory Methods</em></li><li>Nugget #2: <em>Use Builders for Many Parameters</em></li><li>Nugget #3: <em>Enforce Singleton with Private Constructor or Enum</em></li><li>✅ Nugget #4: <em>Make Your Utility Classes Noninstantiable</em></li></ul><blockquote>Noninstantiable classes keep your APIs clean, your intentions clear, and your users safe from themselves.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec5bc2f7491d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Java Nuggets #3: Enforce the Singleton Property with a Private Constructor or an Enum]]></title>
            <link>https://medium.com/@aindrilapolley12/java-nuggets-3-enforce-the-singleton-property-with-a-private-constructor-or-an-enum-785d87bd42a7?source=rss-b5d1e1be876e------2</link>
            <guid isPermaLink="false">https://medium.com/p/785d87bd42a7</guid>
            <category><![CDATA[java-nuggets]]></category>
            <dc:creator><![CDATA[Aindrila Polley]]></dc:creator>
            <pubDate>Sat, 26 Jul 2025 13:22:36 GMT</pubDate>
            <atom:updated>2025-07-26T13:22:36.029Z</atom:updated>
            <content:encoded><![CDATA[<p>In object-oriented programming, a <strong>singleton</strong> is a design pattern that ensures a class has only <strong>one instance</strong> and provides a global point of access to it.</p><p>In Java, it’s surprisingly easy to mess up a singleton implementation — unless you do it the right way.</p><p>This Java Nugget will show you two bulletproof ways to enforce the singleton property:</p><ol><li>Using a <strong>private constructor</strong></li><li>Using an <strong>enum type</strong></li></ol><p>Let’s get into it.</p><h3>🤔 Why Use a Singleton?</h3><ul><li>Caching shared resources (e.g. DB connections, config)</li><li>Ensuring consistent state</li><li>Avoiding repeated instantiation</li></ul><p>But if done wrong, you might accidentally create <strong>multiple instances</strong>, breaking the pattern.</p><h3>🚫 The Wrong Way (Anti-Pattern)</h3><pre>public class ConfigManager {<br>    public static final ConfigManager INSTANCE = new ConfigManager();<br>}</pre><p>Anyone can still do this:</p><pre>ConfigManager config = new ConfigManager(); // ❌ Oops — new instance!</pre><p>The class is still <strong>publicly instantiable</strong>, which violates the singleton principle.</p><h3>✅ The Right Way: Private Constructor</h3><pre>public class ConfigManager {<br>    private static final ConfigManager INSTANCE = new ConfigManager();<br><br>    private ConfigManager() {<br>        // private constructor blocks instantiation<br>    }<br><br>    public static ConfigManager getInstance() {<br>        return INSTANCE;<br>    }<br><br>    public void load() {<br>        System.out.println(&quot;Loading configuration...&quot;);<br>    }<br>}</pre><h4>🔒 Usage:</h4><pre>ConfigManager config = ConfigManager.getInstance();<br>config.load();</pre><p>This works well, but there’s a <strong>catch</strong>…</p><blockquote><em>⚠️ It’s </em><strong><em>not safe against reflection or serialization</em></strong><em> unless extra steps are taken.</em></blockquote><h3>🛡️ The Best Way: Enum Singleton</h3><p>The <strong>most foolproof singleton</strong> in Java is implemented using an enum.</p><h3>✅ Why?</h3><ul><li><strong>Thread-safe</strong> by design</li><li>Immune to <strong>reflection attacks</strong></li><li>Safe from <strong>deserialization tricks</strong></li><li>Short and elegant</li></ul><h3>🔹 Example:</h3><pre>public enum ConfigManager {<br>    INSTANCE;<br><br>    public void load() {<br>        System.out.println(&quot;Loading configuration from enum...&quot;);<br>    }<br>}</pre><h4>🔄 Usage:</h4><pre>ConfigManager.INSTANCE.load();</pre><h4>🧪 Even this won’t break it:</h4><pre>Enum.valueOf(ConfigManager.class, &quot;INSTANCE&quot;); // Still returns same instance</pre><h3>🧠 When to Use Which?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PQqtzL-a4q3MGGfYU28y9w.png" /></figure><h3>🔐 Bonus: Making Constructor-Based Singleton Reflection-Proof</h3><p>If you’re sticking with a private constructor, add this check:</p><pre>private static final ConfigManager INSTANCE = new ConfigManager();<br><br>private ConfigManager() {<br>    if (INSTANCE != null) {<br>        throw new RuntimeException(&quot;Use getInstance() to create the singleton&quot;);<br>    }<br>}</pre><p>But again, <strong>enum handles all this for you.</strong></p><h3>🧩 TL;DR</h3><ul><li>✅ Use a <strong>private constructor</strong> and a <strong>static final instance</strong> for basic singleton needs.</li><li>🔐 Use an <strong>enum singleton</strong> for complete protection.</li><li>🚫 Avoid public constructors for singleton classes.</li><li>💬 If using frameworks like Spring, rely on container-managed singletons.</li></ul><h3>📌 Java Nuggets Recap</h3><ul><li>Nugget #1: <a href="https://medium.com/@aindrilapolley12/java-nuggets-1-why-static-factory-methods-can-be-smarter-than-constructors-4b3e2f3a374f">Prefer Static Factory Methods</a></li><li>Nugget #2: <a href="https://medium.com/@aindrilapolley12/java-nuggets-2-when-constructors-collapse-builders-rescue-2683c9552a94">Use Builder for Many Parameters</a></li><li>✅ Nugget #3: <em>Enforce Singleton with Private Constructor or Enum</em></li></ul><p>Java lets you shoot yourself in the foot with singletons. The enum pattern makes sure you don’t.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=785d87bd42a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Java Nuggets #2: When Constructors Collapse, Builders Rescue]]></title>
            <link>https://medium.com/@aindrilapolley12/java-nuggets-2-when-constructors-collapse-builders-rescue-2683c9552a94?source=rss-b5d1e1be876e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2683c9552a94</guid>
            <category><![CDATA[java-nuggets]]></category>
            <dc:creator><![CDATA[Aindrila Polley]]></dc:creator>
            <pubDate>Sat, 26 Jul 2025 11:04:44 GMT</pubDate>
            <atom:updated>2025-07-26T11:04:44.790Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome back to <strong>Java Nuggets</strong> — your bite-sized guide to writing clean, modern Java.</p><p>In this edition, we tackle a problem every developer faces eventually:</p><blockquote><em>“How do I manage a constructor that takes too many parameters?”</em></blockquote><p>Spoiler: <strong>Don’t. Use a Builder instead.</strong></p><p>In Java, constructors are the go-to way of creating objects. But as the number of parameters increases, things can get… messy.</p><p>If you’ve ever struggled with a constructor that takes five or more parameters — some of them optional — you already know the pain.</p><p>That’s where the <strong>Builder Pattern</strong> comes in.</p><p>Let’s explore why and when you should consider using a builder — and how it makes your code cleaner, safer, and more readable.</p><h3>💥 The Problem with Telescoping Constructors</h3><p>Let’s say you have a class to represent a user’s profile.</p><pre>public class UserProfile {<br>    private final String username;<br>    private final String email;<br>    private final int age;<br>    private final String address;<br>    private final String phone;<br><br>    public UserProfile(String username, String email, int age, String address, String phone) {<br>        this.username = username;<br>        this.email = email;<br>        this.age = age;<br>        this.address = address;<br>        this.phone = phone;<br>    }<br>}</pre><p>Now, what if some of these fields are optional?</p><p>You might end up with <strong>multiple overloaded constructors</strong>, which is known as the <strong>telescoping constructor anti-pattern</strong>:</p><pre>public UserProfile(String username, String email) { ... }<br>public UserProfile(String username, String email, int age) { ... }<br>public UserProfile(String username, String email, int age, String address) { ... }</pre><p>This quickly becomes hard to read, hard to use, and error-prone.</p><h3>😖 The Telescoping Constructor Problem</h3><p>Let’s say you’re modeling a user profile. It starts simply:</p><pre>new UserProfile(&quot;aindrila&quot;, &quot;aindrila@example.com&quot;);</pre><p>Then comes age. Then address. Then phone. Before you know it, you&#39;re deep in constructor overload hell:</p><pre>new UserProfile(&quot;aindrila&quot;, &quot;aindrila@example.com&quot;, 28, &quot;Vilnius&quot;, &quot;+370123456789&quot;);</pre><p>Now imagine remembering the order or which values are optional. Yikes!</p><h3>🧠 Enter the Builder Pattern</h3><p>The <strong>Builder Pattern</strong> helps construct complex objects step-by-step, especially when dealing with optional fields or a large number of parameters.<br>✅ Named methods<br>✅ Flexible and readable syntax<br>✅ Safe object construction<br>✅ Support for optional and required parameters<br>✅ Avoids confusion from parameter ordering</p><h3>✨ Using a Builder in Java</h3><pre>public class UserProfile {<br>    private final String username;<br>    private final String email;<br>    private final int age;<br>    private final String address;<br>    private final String phone;<br><br>    // private constructor<br>    private UserProfile(Builder builder) {<br>        this.username = builder.username;<br>        this.email = builder.email;<br>        this.age = builder.age;<br>        this.address = builder.address;<br>        this.phone = builder.phone;<br>    }<br><br>    // static inner Builder class<br>    public static class Builder {<br>        private final String username;<br>        private final String email;<br>        private int age;<br>        private String address;<br>        private String phone;<br><br>        public Builder(String username, String email) {<br>            this.username = username;<br>            this.email = email;<br>        }<br><br>        public Builder age(int age) {<br>            this.age = age;<br>            return this;<br>        }<br><br>        public Builder address(String address) {<br>            this.address = address;<br>            return this;<br>        }<br><br>        public Builder phone(String phone) {<br>            this.phone = phone;<br>            return this;<br>        }<br><br>        public UserProfile build() {<br>            return new UserProfile(this);<br>        }<br>    }<br>}</pre><h3>🔧 Usage</h3><pre>UserProfile user = new UserProfile.Builder(&quot;aindrila&quot;, &quot;aindrila@example.com&quot;)<br>    .age(28)<br>    .address(&quot;Vilnius, Lithuania&quot;)<br>    .phone(&quot;+370 123456789&quot;)<br>    .build();</pre><h3>🚀 Why Builders Are Better</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qp5N26Xzdr8c825IoqBXqQ.png" /></figure><h3>🛠️ Real-World Examples</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-y3bQHkuCH_6OUQteujKtg.png" /></figure><h3>🚫 When Not to Use a Builder</h3><ul><li>Only 2–3 parameters, all required? Constructor is fine.</li><li>You need super-fast instantiation? Builders add a tiny overhead.</li></ul><p>But if the constructor feels bloated or unclear — <strong>use a builder</strong>.</p><h3>🧠 TL;DR</h3><ul><li><strong>Too many constructor parameters?</strong> → Use a <strong>Builder</strong></li><li><strong>Mix of required and optional fields?</strong> → Builder</li><li><strong>Want clean, readable, future-proof code?</strong> → You guessed it: Builder</li></ul><h3>👇 Java Nuggets is your quick guide to writing better Java, one concept at a time.</h3><p>📌 Follow the series and level up your Java game.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2683c9552a94" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[☕ Java Nuggets #1: Why Static Factory Methods Can Be Smarter Than Constructors]]></title>
            <link>https://medium.com/@aindrilapolley12/java-nuggets-1-why-static-factory-methods-can-be-smarter-than-constructors-4b3e2f3a374f?source=rss-b5d1e1be876e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b3e2f3a374f</guid>
            <category><![CDATA[java-nuggets]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Aindrila Polley]]></dc:creator>
            <pubDate>Thu, 24 Jul 2025 15:24:35 GMT</pubDate>
            <atom:updated>2025-07-26T11:05:44.685Z</atom:updated>
            <content:encoded><![CDATA[<p>When we first learn Java, constructors feel like the natural choice for creating objects. They’re straightforward and familiar. But as we grow as developers and build more complex systems, we start to notice constructors can be… limiting.</p><p>That’s where <strong>static factory methods</strong> shine. They offer cleaner code, better readability, and more control over the object creation process.</p><p>Let’s explore when and why static factory methods can be smarter than constructors — not just academically, but practically.</p><h3>🧩 What Is a Static Factory Method?</h3><p>A <strong>static factory method</strong> is simply a static method that returns an instance of the class.</p><pre>public class User {<br>    private String name;<br>    private Boolean isActive;<br><br>    private User(String name, Boolean isActive) {<br>        this.name = name;<br>        this.isActive = isActive;<br>    }<br><br>    public static User createActiveUser(String name) {<br>        return new User(name, true);<br>    }<br>}</pre><p>Instead of this:</p><pre>User user = new User(&quot;Alice&quot;, true);</pre><p>You might do:</p><pre>User user = User.createActiveUser(&quot;Alice&quot;);</pre><p>Simple shift — big impact.</p><h3>✅ Advantages Over Constructors</h3><h4>1. Descriptive Naming</h4><p>Constructors are bound to the class name. But static methods can have meaningful names:</p><pre>Duration d = Duration.ofMinutes(10);  // Clear<br>Duration d2 = new Duration(0, 0, 600); // What’s 600?</pre><p>You’re not left guessing.</p><h4>2. Controlled Object Creation</h4><p>Static factories can:</p><ul><li><strong>Return cached instances</strong> (e.g., for enums or flyweight)</li><li><strong>Return a subtype</strong>, not always the declared class</li></ul><p>Example:</p><pre>List&lt;String&gt; list = List.of(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;); // Immutable list</pre><p>Behind the scenes, this may return an internal, optimized implementation. With constructors, you’d lose this flexibility.</p><h4>3. Avoid Object Creation Altogether</h4><p>They can <strong>reuse objects</strong>, reducing memory pressure:</p><pre>Boolean b = Boolean.valueOf(&quot;true&quot;);  // Might return cached Boolean.TRUE</pre><h4>4. Encapsulate Logic</h4><p>You can include validation or creation logic inside the static method:</p><pre>public static User createActiveUser(String name) {<br>    if (name == null || name.isBlank()) throw new IllegalArgumentException();<br>    return new User(name, true);<br>}</pre><p>Cleaner than stuffing logic into constructors.</p><h3>🧠 Common Naming Patterns in Java</h3><p>The JDK uses consistent naming conventions for factory methods to hint at their behavior. Let’s break them down.</p><h3>🔸 from — Type Conversion</h3><p>Used when converting from one type to another.</p><pre>Date date = Date.from(Instant.now());</pre><h3>🔸 of — Aggregation of Parameters</h3><p>Used when combining multiple values into one object.</p><pre>Set&lt;Rank&gt; faceCards = EnumSet.of(Rank.JACK, Rank.QUEEN, Rank.KING);</pre><h3>🔸 valueOf — More Verbose Conversion</h3><p>Often used for parsing or wrapping primitives.</p><pre>BigInteger big = BigInteger.valueOf(123);</pre><h3>🔸 getInstance — Return Cached or Derived Instance</h3><p>Used when an instance is based on parameters or internal logic.</p><pre>StackWalker walker = StackWalker.getInstance(Set.of(StackWalker.Option.RETAIN_CLASS_REFERENCE));</pre><h3>🔸 newInstance / create — Always Return a New Object</h3><p>Used when a fresh instance is required every time.</p><pre>int[] arr = (int[]) Array.newInstance(int.class, 5);</pre><h3>🔸 getType — Factory in a Different Class (Shared Instance)</h3><p>Used when the method lives in a helper or utility class.</p><pre>FileStore store = Files.getFileStore(Path.of(&quot;.&quot;));</pre><h3>🔸 newType — New Object from a Different Class</h3><p>Same as above, but returns a new object.</p><pre>BufferedReader reader = Files.newBufferedReader(Path.of(&quot;file.txt&quot;));</pre><h3>🔸 type — Concise External Factory</h3><p>A shorter version of getType or newType.</p><pre>List&lt;String&gt; list = Collections.list(someEnumeration);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8S12KDM9gre0E6ye0LGF4Q.png" /></figure><h3>⚠️ When to Stick With Constructors</h3><p>Despite the benefits, constructors still have their place:</p><ul><li>When the class is meant to be extended</li><li>When simplicity is key and object creation is trivial</li><li>For frameworks that use reflection (e.g., JPA, Spring)</li></ul><p>Use static factory methods <strong>when clarity or control matters</strong>. Don’t overuse them for the sake of cleverness.</p><h3>🔁 Real-World Analogy</h3><p>Think of constructors as a raw “new” button. Static factory methods are like a smart assistant — helping you get the exact kind of object you need, without the guesswork.</p><h3>💡 Takeaway</h3><blockquote>Static factory methods make your code more readable, more flexible, and often more efficient.</blockquote><p>You don’t have to give up constructors entirely — just <strong>know when to reach for something smarter.</strong></p><p>📌 <strong>This is part of the </strong><a href="https://medium.com/@aindrilapolley12/java-nuggets-a-curated-series-of-practical-java-insights-a44801bb208e"><strong>Java Nuggets Series</strong> </a>— a growing collection of practical, focused Java insights.<br>Follow the tag #java-nuggets to stay updated.<br>Next up: <em>“When Constructors Collapse, Builders Rescue”</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b3e2f3a374f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[☕ Java Nuggets: A Curated Series of Practical Java Insights]]></title>
            <link>https://medium.com/@aindrilapolley12/java-nuggets-a-curated-series-of-practical-java-insights-a44801bb208e?source=rss-b5d1e1be876e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a44801bb208e</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java-nuggets]]></category>
            <dc:creator><![CDATA[Aindrila Polley]]></dc:creator>
            <pubDate>Thu, 24 Jul 2025 14:29:12 GMT</pubDate>
            <atom:updated>2025-07-24T15:27:55.983Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b9HVeQzZNjmQtekW27OJ-Q.jpeg" /></figure><blockquote>Welcome to Java Nuggets — a growing collection of short, sharp, and practical insights for Java developers. This series is meant to help you make better design decisions, understand trade-offs, and apply the right tools for the right use case in real-world projects.</blockquote><h3>📚 <strong>Java Nuggets Series Index</strong>:</h3><p>All About Creating and Destroying Objects<br>1.<a href="https://medium.com/@aindrilapolley12/java-nuggets-1-why-static-factory-methods-can-be-smarter-than-constructors-4b3e2f3a374f"><strong>Why Static Factory Methods Can Be Smarter Than Constructors</strong></a><strong><br></strong><em>Clarity, flexibility, and naming advantages in object creation.<br>2.</em><strong>Taming Constructor Chaos with the Builder Pattern</strong><br> <em>Clean, readable ways to build complex objects.<br>3.</em><strong>Creating Singletons the Right Way: Private Constructors vs Enums</strong><br> <em>Safe and effective singleton implementations in Java.<br>4.</em><strong>Making Utility Classes Truly Non-Instantiable</strong><br> <em>How a private constructor prevents misuse.<br>5.</em><strong>Say Goodbye to Hardcoded Resources with Dependency Injection</strong><br> <em>Loosely coupled design for cleaner, testable code.<br>6.</em><strong>The Hidden Cost of Unnecessary Object Creation</strong><br> <em>Improve performance by creating only what you need.<br>7.</em><strong>Watch Out for Memory Leaks: Clear Those Obsolete References</strong><br> <em>Why forgetting to null can quietly eat up memory.<br>8.</em><strong>Finalizers &amp; Cleaners: Why They’re Not Your Friends</strong><br> <em>Risks of relying on them and what to do instead.<br>9.</em><strong>Try-with-Resources: The Cleaner Way to Handle Resources</strong><br> <em>Less boilerplate, fewer bugs, better resource management.</em></p><h3>🧭 How to Use This Series</h3><p>Each post is independent and bite-sized — ideal for quick reading and deep reflection. Together, they cover:</p><ul><li>Design patterns and object creation</li><li>Memory management tips</li><li>Resource handling best practices</li><li>Cleaner, testable Java development</li></ul><p>📌 <strong>Bookmark this page</strong> or follow me on Medium for updates. New nuggets will be added as the series grows.</p><h3>🔖 Follow the Tag</h3><p>All posts are tagged with #java-nuggets — click here to see the full list once your posts are live.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a44801bb208e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Real-World Integration Testing with WireMock, Redis & Spring Boot]]></title>
            <link>https://medium.com/@aindrilapolley12/real-world-integration-testing-with-wiremock-redis-spring-boot-ca86628d7a62?source=rss-b5d1e1be876e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca86628d7a62</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[wiremock]]></category>
            <category><![CDATA[testcontainer]]></category>
            <category><![CDATA[integration-testing]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Aindrila Polley]]></dc:creator>
            <pubDate>Tue, 10 Jun 2025 23:02:47 GMT</pubDate>
            <atom:updated>2025-06-12T14:31:50.263Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RdQIWP6EE5yEmKSGQXImpg.png" /></figure><blockquote>“Mocking without madness” — that’s what this setup is about.</blockquote><p>Integration testing in microservices isn’t just about hitting endpoints. It’s about creating <strong>controlled environments</strong>, simulating real dependencies, and ensuring clean test runs.</p><p>In this post, I’ll walk through how we set up a robust test framework using:</p><p>✅ <strong>WireMock</strong> (to mock external APIs)</p><p>✅ <strong>Testcontainers Redis</strong></p><p>✅ <strong>Custom JUnit extensions</strong></p><p>✅ <strong>Spring Boot IntegrationTest annotations</strong></p><h3>🧩 Problem Statement</h3><p>When building a sample service in a Spring Boot app, I needed to test:</p><blockquote><em>✔️ Will the service respond correctly when the external sample API is called?</em></blockquote><p>But I didn’t want to hit a live server or create a flaky test that relied on network conditions.</p><h3>🧪 The Solution: A Fully Isolated Integration Test Setup</h3><p>I designed an environment where:</p><ul><li>The <strong>external API is mocked using WireMock</strong>.</li><li>A <strong>Redis instance runs in Docker</strong> via Testcontainers.</li><li>Spring Boot context spins up just like production (with overrides).</li><li>Each test runs with a <strong>fresh Redis state</strong>.</li></ul><p>Here’s what it looks like:</p><p>📁 <strong>Folder &amp; Class Structure (Key Highlights)</strong></p><pre>src/test/<br>├── java/com/example/docker/app/<br>│   ├── AbstractWireMockTest.java<br>│   ├── IntegrationTest.java<br>│   ├── NoKeepAliveTransformer.java<br>│   ├── RedisExtension.java<br>│   ├── RedisContainer.java<br>│   ├── RequestAwareExtension.java<br>│   ├── SpringBootDockerApplicationTests.java<br>│   ├── WiremockConfiguration.java<br>│   └── service/SampleServiceImplIntegrationTest.java<br>└── resources/stubs/SampleServiceImplIntegrationTest/sample-data.json</pre><h3>🔨 How It Works — Step by Step</h3><h3>1. 🧱 AbstractWireMockTest</h3><p>This is the base class for all integration tests needing API mocks:</p><pre>@AutoConfigureWireMock(port = 0)<br>public class AbstractWireMockTest {<br>    @Autowired protected WireMockServer wireMockServer;<br><br>    @BeforeEach<br>    void setUpWireMock() {<br>        wireMockServer.resetToDefaultMappings();<br>    }<br><br>    protected void addStub(String path, String file) throws Exception {<br>        // loads JSON stub file from /stubs/** and registers with WireMock<br>    }<br>}</pre><h3>2. 🧪 IntegrationTest Annotation</h3><p>Custom annotation to simplify test configuration:</p><pre>@Target(TYPE)<br>@Retention(RUNTIME)<br>@ActiveProfiles(&quot;integration-test&quot;)<br>@SpringBootTest(webEnvironment = RANDOM_PORT)<br>@ExtendWith({RedisExtension.class, RequestAwareExtension.class})<br>public @interface IntegrationTest {}</pre><p>It bootstraps Spring context, enables mocks, and includes:</p><ul><li>RedisExtension: starts a Docker Redis instance.</li><li>RequestAwareExtension: injects a mock servlet request.</li></ul><h3>3. 🐳 Redis Testcontainers</h3><pre>public class RedisContainer extends GenericContainer&lt;RedisContainer&gt; {<br><br>    private static final int hostPort = 6388;<br><br>    public RedisContainer() {<br>        super(&quot;redis:6.0.9-alpine&quot;);<br>    }<br><br>    @Override<br>    protected void configure() {<br>        super.configure();<br>        addFixedExposedPort(hostPort, 6378);<br>        waitingFor(Wait.forLogMessage(&quot;Ready to accept connections.&quot;, 1));<br>    }<br>}</pre><p>After each test:</p><pre>redis-cli FLUSHALL</pre><p>This ensures <strong>no state leakage</strong> between tests.</p><h3>4. 🌐 Stub Example (sample-data.json)</h3><pre>{<br>  &quot;request&quot;: {<br>    &quot;method&quot;: &quot;GET&quot;,<br>    &quot;urlPath&quot;: &quot;/sample/a12zx&quot;<br>  },<br>  &quot;response&quot;: {<br>    &quot;status&quot;: 200,<br>    &quot;headers&quot;: {<br>      &quot;Content-Type&quot;: &quot;application/json&quot;<br>    },<br>    &quot;body&quot;: &quot;{ \&quot;id\&quot;: \&quot;a12zx\&quot;, \&quot;name\&quot;: \&quot;sample 1\&quot; }&quot;<br>  }<br>}</pre><p>This makes GET /sample/a12zx return a fake but controlled response. Super useful for validation!</p><h3>5. ✅ Actual Test in Action</h3><pre>@SpringBootTest<br>@IntegrationTest<br>public class SampleServiceImplIntegrationTest extends AbstractWireMockTest {<br><br>    private static final String STUBS_PATH = &quot;/stubs/SampleServiceImplIntegrationTest&quot;;<br><br>    @Autowired<br>    private SampleService sampleService;<br><br>    @Test<br>    void whenValidRequestProvided_shouldReturnResponse() throws Exception {<br>        addStub(STUBS_PATH, &quot;sample-data&quot;);<br><br>        final String id = &quot;a12zx&quot;;<br><br>        final SampleData expectedSampleData = SampleData.builder()<br>                .id(&quot;a12zx&quot;)<br>                .name(&quot;sample 1&quot;)<br>                .build();<br><br>        final SampleData response = sampleService.getSample(&quot;a12zx&quot;);<br><br>        assertThat(response).isEqualTo(expectedSampleData);<br>        wireMockServer.verify(1, getRequestedFor(urlPathMatching(&quot;/sample/&quot; + id)));<br>    }<br>}</pre><h3>⚙️ Bonus: Connection: close Header Hack</h3><p>Added a ResponseDefinitionTransformer to disable keep-alive and avoid issues with reused connections:</p><pre>public class NoKeepAliveTransformer extends ResponseDefinitionTransformer {<br>    @Override<br>    public ResponseDefinition transform(...) {<br>        return ResponseDefinitionBuilder<br>            .like(responseDefinition)<br>            .withHeader(&quot;Connection&quot;, &quot;close&quot;)<br>            .build();<br>    }<br>}</pre><h3>🎯 Why This Setup Works Great</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qs2KKPBDfkq-gO51H8BpzQ.png" /></figure><h4>📘 TL;DR</h4><p>This setup enables you to:</p><ul><li>Write stable integration tests for HTTP services.</li><li>Avoid flakiness and external service dependency.</li><li>Have full control of request/response.</li><li>Maintain test readability and structure.</li></ul><h4>🗣️ Want More?</h4><p>I’d be happy to:</p><ul><li>Share a GitHub repo</li><li>Walk through Spring Cloud Contract integration</li><li>Explain how to auto-generate stub mappings</li></ul><p>Just drop a comment or message me on <a href="https://www.linkedin.com/in/aindrilapolley/">LinkedIn</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca86628d7a62" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Evolution of Java Concurrency: From Threads to Structured Concurrency (Java 7–21)]]></title>
            <link>https://medium.com/@aindrilapolley12/the-evolution-of-java-concurrency-from-threads-to-structured-concurrency-java-7-21-e2c6e3bd7383?source=rss-b5d1e1be876e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2c6e3bd7383</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[threading-in-java]]></category>
            <category><![CDATA[java21]]></category>
            <category><![CDATA[structured-concurrency]]></category>
            <category><![CDATA[completablefuture]]></category>
            <dc:creator><![CDATA[Aindrila Polley]]></dc:creator>
            <pubDate>Tue, 20 May 2025 21:51:00 GMT</pubDate>
            <atom:updated>2025-05-20T21:51:00.432Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*1bjBgTxmzIIRZat47xZPkg.jpeg" /></figure><blockquote>Java has come a long way since the days of manually managing threads. This post traces how concurrency and multithreading evolved across Java 7, 8, 11, 17, and 21 — so you can write better, safer, and more maintainable asynchronous code.</blockquote><h3><strong>Introduction</strong></h3><p>Concurrency is not just a buzzword — it’s a core requirement for building performant and scalable Java applications. But how we write concurrent code in Java has dramatically evolved from version 7 to 21. Java has introduced tools that simplify thread management, improve readability, and make error handling cleaner.</p><p>If you’re a backend developer or Java practitioner, this post will walk you through what changed in Java 7, 8, 11, 17, and 21 with real-world scenarios and code samples to help you write better, safer concurrent programs.</p><h3>Java 7: Fork/Join Framework and Managing Threads</h3><blockquote>“Divide and conquer” was the motto.</blockquote><h3>What It Introduced</h3><ul><li>ForkJoinPool (JSR 166y)</li><li>RecursiveTask and RecursiveAction</li><li>Work-stealing algorithm for parallelism</li></ul><p><strong>Why It Mattered:</strong> Before Java 7, thread management was manual and error-prone. ExecutorService was a step forward but didn&#39;t scale well for recursive or divide-and-conquer tasks. You had to handle Thread creation, management, and synchronization yourself.</p><p><strong>What Came In:</strong> Fork/Join Framework</p><p>Fork/Join allowed:</p><ul><li>Decomposing problems recursively</li><li>Utilizing all CPU cores efficiently</li><li>Fine-grained task parallelism</li></ul><h4>Fork/Join Basics</h4><p>It was built to solve CPU-intensive, divide-and-conquer tasks by breaking them into smaller subtasks that can be processed in parallel.</p><pre>class FibonacciTask extends RecursiveTask&lt;Integer&gt; {<br>    int n;<br>    FibonacciTask(int n) { this.n = n; }<br><br>    @Override<br>    protected Integer compute() {<br>        if (n &lt;= 1) return n;<br>        FibonacciTask f1 = new FibonacciTask(n - 1);<br>        f1.fork();<br>        FibonacciTask f2 = new FibonacciTask(n - 2);<br>        return f2.compute() + f1.join();<br>    }<br>}<br><br>ForkJoinPool pool = new ForkJoinPool();<br>int result = pool.invoke(new FibonacciTask(10));</pre><p><strong>Key Takeaway:</strong> ForkJoinPool is optimized for work-stealing and is best used when tasks can be recursively split. But it’s still fairly low-level.</p><p><strong>Real-World Use Case: </strong>Image processing, matrix operations, parallel sorting.</p><p><strong>Downside</strong>: Harder debugging, steep learning curve, poor composability.</p><h3>Java 8: The Functional Awakening</h3><blockquote>“Concurrency meets declarative programming.”</blockquote><p><strong>Why It Mattered:</strong> Java 8 made asynchronous workflows readable. CompletableFuture enabled <strong>non-blocking chains</strong>, error handling, and composition. Before this, working with Future felt like using a toy hammer in a construction site. Java 8 shifted the paradigm with lambdas and functional-style APIs, making asynchronous programming less verbose and more composable.</p><p><strong>What Came In:</strong></p><ul><li>CompletableFuture</li><li>Parallel Streams</li></ul><p><strong>CompletableFuture</strong></p><p>No more blocking with Future.get()! CompletableFuture enables pipelines of async tasks.</p><pre>CompletableFuture.supplyAsync(() -&gt; fetchUser())<br>    .thenApply(user -&gt; enrich(user))<br>    .thenAccept(enriched -&gt; display(enriched));</pre><p><strong>Pro Tip:</strong> Always provide a custom ExecutorService if using supplyAsync extensively in production.</p><p><strong>Parallel Streams</strong></p><pre>List&lt;String&gt; results = items.parallelStream()<br>    .map(this::transform)<br>    .collect(Collectors.toList());</pre><p><strong>Warning:</strong> Not suitable for all workloads. Be careful with shared resources or IO-bound tasks.</p><p><strong>Pros</strong></p><ul><li>Declarative</li><li>Composable</li><li>Built-in exception handling (exceptionally, handle, whenComplete)</li></ul><p><strong>Caution</strong></p><ul><li>Default thread pool is ForkJoinPool.commonPool()—be careful with blocking operations.</li><li>parallelStream() is <strong>not always faster</strong>. Use for CPU-bound, stateless, data-parallel tasks.</li></ul><p><strong>Real-World Use Case</strong></p><ul><li>Async service orchestration</li><li>Non-blocking I/O</li><li>UI/event pipelines</li></ul><h3>Java 11: Better Async HTTP</h3><blockquote>“Less hype, more substance.”</blockquote><p><strong>Why It Mattered:</strong> Networking and IO are major concurrency bottlenecks. Java 11’s HTTP client supports true non-blocking IO.</p><ul><li>Aligned Java with modern reactive APIs</li><li>Foundation for frameworks like Spring WebFlux, Micronaut, Vert.x</li></ul><p>Java 11 quietly prepared the platform for more <strong>non-blocking, event-driven architectures</strong>.</p><p><strong>What Came In:</strong> HttpClient with async APIs using CompletableFuture</p><pre>HttpClient client = HttpClient.newHttpClient();<br>HttpRequest req = HttpRequest.newBuilder(URI.create(url)).build();<br><br>client.sendAsync(req, BodyHandlers.ofString())<br>    .thenApply(HttpResponse::body)<br>    .thenAccept(System.out::println);</pre><p><strong>Use Case:</strong> Microservices, async APIs, webhooks</p><h3>Java 17: Refinements and Production-Readiness</h3><blockquote>“Stability &gt; novelty.”</blockquote><p><strong>Why It Mattered:</strong> While not heavy on new APIs, Java 17 solidified and optimized existing concurrency tools, becoming the new LTS.</p><p><strong>Notable Additions:</strong></p><ul><li>Enhanced Thread.onSpinWait() for busy-wait performance</li><li>Memory improvements for async workloads</li><li>Preview of sealed classes — useful in modeling concurrent result types</li></ul><p><strong>When to Use:</strong> If you’re building performance-sensitive systems (low-latency trading, gaming backends), these low-level enhancements matter.</p><h3>Practical Takeaways</h3><ul><li>Java 17 is an <strong>excellent LTS base</strong> if you want both performance and compatibility</li><li>Pairs well with libraries like Project Reactor, RxJava, and structured concurrency (backported)</li></ul><h3>Java 21: Structured Concurrency (Preview)</h3><blockquote>“Concurrency is finally readable.”</blockquote><p><strong>Why It Mattered:</strong> Managing thread lifecycles has always been messy. Java 21 introduces <em>Structured Concurrency</em> — where tasks are grouped, managed, and terminated together.</p><p><strong>What Came In:</strong> StructuredTaskScope</p><pre>try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {<br>    Future&lt;User&gt; user = scope.fork(() -&gt; findUser());<br>    Future&lt;Order&gt; order = scope.fork(() -&gt; fetchOrders());<br><br>    scope.join();           // Wait for all<br>    scope.throwIfFailed();  // Propagate exception if any<br><br>    use(user.resultNow(), order.resultNow());<br>}</pre><p><strong>Why It’s a Game-Changer:</strong></p><ul><li>Avoids thread leaks</li><li>Simplifies error propagation</li><li>Easier to reason about concurrent flows, making code more readable</li></ul><p>Inspired by other ecosystems (e.g., Kotlin coroutines), this API treats multiple concurrent tasks as a <em>unit</em>, ensuring they’re started, monitored, and cancelled together.</p><p><strong>Real-World Use Case:</strong> Microservices making multiple downstream calls in parallel (e.g., loading user profile + transaction history + notifications)</p><p><strong>Real Benefits</strong></p><ul><li>Cancel all sibling tasks if one fails</li><li>One exit point, cleaner code</li><li>Improved observability and testing</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JqZzYQdCW4qNGTo96W-dRQ.png" /></figure><blockquote>Java’s concurrency journey is a reflection of its maturity. The language has moved from boilerplate-heavy threading to intuitive, safe, and composable concurrency models. Whether you’re building REST APIs or event-driven systems, knowing which concurrency tool to pick for the job can help you write faster, safer, and cleaner code.</blockquote><blockquote>If you’re on Java 8+, it’s time to embrace CompletableFuture. If you&#39;re exploring Java 21+, Structured Concurrency will change how you manage threads for good.</blockquote><p><strong>Coming Soon:</strong> In the next post, I’ll show how to use Virtual Threads alongside structured concurrency for high-throughput applications with fewer resources.</p><p><strong>Let me know if you’d like a GitHub repo with these code examples!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2c6e3bd7383" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Multithreading and Concurrency in Java: Concepts, Pitfalls, and Best Practices]]></title>
            <link>https://medium.com/@aindrilapolley12/demystifying-multithreading-and-concurrency-in-java-concepts-pitfalls-and-best-practices-eb9c168d88e6?source=rss-b5d1e1be876e------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb9c168d88e6</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Aindrila Polley]]></dc:creator>
            <pubDate>Tue, 20 May 2025 21:06:27 GMT</pubDate>
            <atom:updated>2025-05-20T21:06:27.815Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aaTgw_F5WGN4GEXbQYTtCw.png" /></figure><blockquote>In the age of multi-core processors and real-time systems, concurrency has become a cornerstone of modern software development. Whether you’re building a high-throughput backend service or a data pipeline that processes millions of events per minute, <strong>understanding multithreading and concurrency in Java is no longer optional — it’s essential.</strong></blockquote><blockquote>In this post, I’ll walk you through the fundamentals of concurrency, explore Java’s threading model, highlight common pitfalls, and share actionable best practices.</blockquote><h3>Threads and Processes</h3><p>Let’s lay the foundation:</p><ul><li>A <strong>process</strong> is an independent execution unit with its own memory space.</li><li>A <strong>thread</strong> is a lightweight unit of execution within a process. Multiple threads share the same memory, which enables faster communication but increases the risk of synchronization issues.</li></ul><p>In Java, multithreading is built right into the language, starting from the Thread class and extending into powerful abstractions like Executors, ForkJoinPool, and CompletableFuture.</p><h3>Creating Threads in Java</h3><p>There are two common ways to create threads:</p><h4>1. Extending the Thread class</h4><pre>class MyThread extends Thread {<br>    public void run() {<br>        System.out.println(&quot;Running in: &quot; + Thread.currentThread().getName());<br>    }<br>}<br><br>new MyThread().start();</pre><h4>2. Implementing the Runnable Interface</h4><pre>Runnable task = () -&gt; System.out.println(&quot;Runnable thread: &quot; + Thread.currentThread().getName());<br>new Thread(task).start();</pre><h3>Understanding the Thread Lifecycle</h3><p>Threads have a defined lifecycle:</p><ol><li><strong>New</strong>: Created but not started.</li><li><strong>Runnable</strong>: Ready to run, waiting for CPU time.</li><li><strong>Running</strong>: Currently executing.</li><li><strong>Blocked/Waiting</strong>: Waiting for resources or signals.</li><li><strong>Terminated</strong>: Execution completed.</li></ol><h3>Why Concurrency Matters</h3><p>Traditionally, applications were designed to run tasks sequentially. But with modern CPUs offering multiple cores, sequential execution leaves performance on the table. Concurrency helps us break down tasks and run them efficiently across available cores — <strong>leading to better CPU utilization, improved responsiveness, and reduced latency</strong>.</p><h3>Concurrency vs Parallelism</h3><p>It’s easy to confuse these two — but they serve different goals:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SGPIVy6-ogl5gZEleBISBg.png" /></figure><p>Java supports both models, and the key is knowing <strong>when</strong> and <strong>how</strong> to use them.</p><h3>Common Pitfalls in Multithreading</h3><p>Concurrency is hard. Some classic issues you’ll face:</p><h4>1. Race Conditions</h4><p>Two threads access and modify shared data simultaneously, causing unpredictable results.</p><h4>2. Deadlocks</h4><p>Two or more threads hold locks and wait for each other to release — leading to an infinite wait.</p><h4>3. Livelocks</h4><p>Threads are not blocked but keep changing their state in response to each other — yet no useful work gets done.</p><h4>4. Starvation</h4><p>Some threads never get CPU time or resources because others dominate the system.</p><h3>Making Your Code Thread-Safe</h3><h4>1. synchronized Keyword</h4><p>Ensures only one thread can access a block/method at a time.</p><pre>public synchronized void increment() {<br>    count++;<br>}</pre><p>Use with caution — overusing synchronized can lead to performance bottlenecks and deadlocks.</p><h4>2. volatile Keyword</h4><p>Ensures visibility of changes across threads — but <strong>doesn’t guarantee atomicity</strong>.</p><pre>private volatile boolean flag = true;</pre><p>Best used for flags and signals, not counters or compound operations.</p><h4>3. Explicit Locks (ReentrantLock)</h4><p>Provides more control than synchronized — with features like timeout, interruptibility, and fairness.</p><pre>Lock lock = new ReentrantLock();<br>lock.lock();<br>try {<br>    // critical section<br>} finally {<br>    lock.unlock();<br>}</pre><h3>The Executor Framework</h3><p>Instead of manually creating and managing threads, Java provides a powerful abstraction via the <strong>Executor framework</strong>.</p><h4>Fixed Thread Pool</h4><pre>ExecutorService executor = Executors.newFixedThreadPool(5);<br>executor.submit(() -&gt; System.out.println(&quot;Task executed&quot;));<br>executor.shutdown();</pre><h4>Callable and Future</h4><p>Use when you want to return results from a thread.</p><pre>Callable&lt;Integer&gt; task = () -&gt; 42;<br>Future&lt;Integer&gt; future = executor.submit(task);<br>System.out.println(future.get()); // blocks until result is available</pre><h3>CompletableFuture: Asynchronous Magic (Java 8+)</h3><p>CompletableFuture allows you to build non-blocking, asynchronous pipelines.</p><pre>CompletableFuture.supplyAsync(() -&gt; &quot;Hello&quot;)<br>    .thenApply(s -&gt; s + &quot; World&quot;)<br>    .thenAccept(System.out::println);</pre><p>Supports chaining, exception handling, combining tasks, and more — without the callback hell.</p><h3>Best Practices for Multithreaded Code</h3><blockquote>Writing concurrent code is not just about spinning up multiple threads — it’s about doing it <em>safely, efficiently</em>, and in a way that’s <em>maintainable</em>.</blockquote><p>Below are some in-depth practices that can help you write robust multithreaded code in Java:</p><h4>1. Avoid Shared Mutable State Whenever Possible</h4><p>The root cause of most concurrency bugs? Shared mutable state.</p><p>When multiple threads read/write to the same variable or data structure without proper synchronization, the results can be inconsistent and unpredictable.</p><ul><li>Prefer <em>immutable</em> data structures.</li><li>Pass data through <strong>thread-local storage</strong> or via <strong>message-passing</strong> (like queues).</li><li>Don’t rely on atomic reads/writes without guarantees of atomicity.</li></ul><h4>2. Use High-Level Concurrency APIs</h4><p>Instead of managing threads manually using Thread, prefer higher-level constructs:</p><ul><li>Use ExecutorService to manage thread pools.</li><li>Use CompletableFuture for async workflows.</li><li>Use ForkJoinPool for parallel data processing (especially with recursive tasks).</li><li>Use java.util.concurrent collections (ConcurrentHashMap, BlockingQueue) to manage data sharing safely.</li></ul><p>These abstractions <strong>reduce boilerplate</strong> and minimize the chances of concurrency-related bugs.</p><h4>3. Favor Composition over Synchronization</h4><p>Lock-based synchronization (synchronized, Lock) is prone to:</p><ul><li>Deadlocks</li><li>Thread contention</li><li>Debugging nightmares</li></ul><p>A better approach is to <strong>design components that don’t need locks in the first place</strong>:</p><ul><li>Use immutable objects.</li><li>Split tasks so that each thread works on a separate chunk of data.</li><li>Consider the Actor model or message queues (e.g., BlockingQueue) for inter-thread communication.</li></ul><h4>4. Avoid Blocking Calls in Async Pipelines</h4><p>Blocking operations (Thread.sleep(), future.get(), InputStream.read()) in an asynchronous pipeline can freeze your threads, wasting CPU and making your app unresponsive.</p><p>If you’re using CompletableFuture or reactive libraries like Reactor or RxJava:</p><ul><li>Avoid .get() — use .thenApply(), .thenCompose() etc.</li><li>Prefer non-blocking alternatives (e.g., HttpClient in Java 11+).</li></ul><h4>5. Use Thread-Safe Data Structures</h4><p>Java provides several thread-safe collections:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m1b4XJSxQlBVXckm13d3rA.png" /></figure><p>These collections are optimized and tested for concurrency. Avoid hand-rolling your own data structures unless you really need to.</p><h4>6. Always Shut Down Your Executors</h4><p>Forgetting to shut down an ExecutorService can lead to resource leaks and hanging applications.</p><pre>executor.shutdown(); // Graceful<br>executor.shutdownNow(); // Forceful</pre><p>Use try-finally blocks or better yet, create a utility class to auto-manage shutdowns.</p><h4>7. Use Timeouts and Interrupts</h4><p>Avoid methods that block forever. Always use timeouts when:</p><ul><li>Waiting for a Future: future.get(1, TimeUnit.SECONDS)</li><li>Acquiring a lock: lock.tryLock(100, TimeUnit.MILLISECONDS)</li><li>Polling queues: queue.poll(timeout, TimeUnit.SECONDS)</li></ul><p>This prevents threads from becoming unresponsive and improves fault tolerance.</p><h4>8. Monitor, Profile, and Test Concurrent Code</h4><p>Use tools like:</p><ul><li><strong>VisualVM</strong> / <strong>JConsole</strong>: Inspect thread counts, CPU usage, memory.</li><li><strong>Flight Recorder (JFR)</strong>: Low-overhead profiling built into the JDK.</li><li><strong>Thread dumps</strong>: Analyze blocked or deadlocked threads in production.</li></ul><p>Also:</p><ul><li>Write <strong>stress tests</strong> using frameworks like jcstress.</li><li>Use ThreadMXBean for thread-level metrics.</li></ul><h4>9. Be Mindful of Thread-Safety in Third-Party Libraries</h4><p>Not all libraries are thread-safe by default — always check the documentation.</p><p>For example:</p><ul><li>SimpleDateFormat is <strong>not thread-safe</strong>.</li><li>StringBuilder is not thread-safe, while StringBuffer is (but slower).</li></ul><p>If unsure, use thread-local variables or synchronization wrappers.</p><h4>10. Keep It Simple</h4><p>Simplicity is underrated in concurrency. If your concurrency solution is clever, it’s probably wrong.</p><blockquote><strong>Rule of thumb</strong>: If it’s hard to reason about, it’s hard to maintain.</blockquote><p>Favour readability, avoid over-engineering, and <strong>fail fast</strong> when something breaks.</p><h3>When to Use Concurrency</h3><p>While concurrency sounds exciting, it’s not always necessary. Knowing when to introduce concurrency can help avoid unnecessary complexity.</p><p>Let’s break down the scenarios:</p><h4>Use Concurrency When…</h4><h4>1. You Have CPU-Bound Tasks</h4><p>Examples:</p><ul><li>Heavy computations</li><li>Image or video processing</li><li>Data compression/encryption</li></ul><blockquote>Solution: Break the task into chunks and run them in parallel using a thread pool or ForkJoinPool.</blockquote><h4>2. You Have I/O-Bound Operations</h4><p>Examples:</p><ul><li>Reading/writing files</li><li>Making network calls</li><li>Database queries</li></ul><blockquote>Solution: Use thread pools to run these I/O tasks concurrently, or switch to <strong>non-blocking</strong> frameworks like java.nio, Netty, or Spring WebFlux.</blockquote><h4>3. You Want to Keep UI or Main Thread Responsive</h4><p>If you’re building GUI applications or servers, you don’t want the main thread to be blocked.</p><blockquote>Solution: Offload long-running or blocking tasks to worker threads using ExecutorService or CompletableFuture.</blockquote><h4>4. You Have Event-Driven or Reactive Requirements</h4><p>Examples:</p><ul><li>Real-time systems (e.g., stock trading)</li><li>Streaming apps (e.g., Kafka consumers)</li><li>UIs with multiple input sources</li></ul><blockquote>Solution: Use a reactive programming model (Project Reactor, RxJava, or native Flow API from Java 9+).</blockquote><h3>Don’t Use Concurrency When…</h3><h4>Your App Doesn’t Do Much Work</h4><p>Spawning threads for trivial tasks adds overhead. A simple loop might be faster and safer.</p><h4>You’re Not Managing Shared State Correctly</h4><p>Introducing concurrency without proper synchronization or understanding can lead to subtle bugs that are hard to reproduce and fix.</p><h4>You Just Want to “Speed Up” Something Without Measuring</h4><p>If you haven’t measured the bottleneck, throwing threads at the problem won’t help — and might hurt.</p><blockquote>Multithreading is a powerful feature in Java — but with great power comes great complexity. Understanding the fundamentals, mastering the APIs, and following best practices can go a long way in writing safe and scalable concurrent code.</blockquote><blockquote>In the next post, I’ll explore how Java’s concurrency model has <strong>evolved from Java 7 to Java 21</strong> — from Fork/Join to Virtual Threads.</blockquote><blockquote><strong>Follow me</strong> to stay updated on that, and feel free to drop your thoughts or questions in the comments.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb9c168d88e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>