<?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 priyanka pruthi on Medium]]></title>
        <description><![CDATA[Stories by priyanka pruthi on Medium]]></description>
        <link>https://medium.com/@priyankapruthe?source=rss-95172fd0035f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*pGV66CpBwfDPRWNN</url>
            <title>Stories by priyanka pruthi on Medium</title>
            <link>https://medium.com/@priyankapruthe?source=rss-95172fd0035f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 23:35:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@priyankapruthe/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[Kafka Consumer Lag Explained: How to Monitor, Reduce & Recover]]></title>
            <link>https://medium.com/@priyankapruthe/kafka-consumer-lag-explained-how-to-monitor-reduce-recover-db28c20b7b31?source=rss-95172fd0035f------2</link>
            <guid isPermaLink="false">https://medium.com/p/db28c20b7b31</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[kafka-consumer]]></category>
            <category><![CDATA[kafka-lag]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[priyanka pruthi]]></dc:creator>
            <pubDate>Tue, 05 Aug 2025 07:52:50 GMT</pubDate>
            <atom:updated>2025-08-05T08:03:27.032Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5-vXQPj4K7VDlmbOUXeueQ.png" /></figure><p>Apache Kafka is the backbone of many real-time systems. But what happens when your consumers fall behind? Enter <strong>consumer lag</strong> — one of the most critical (and often misunderstood) metrics in Kafka.</p><p>This guide walks you through <strong>consumer lag</strong>, <strong>offset management</strong>, real-world <strong>recovery strategies</strong>, <strong>AWS MSK metrics</strong>, and actionable best practices with visuals and examples.</p><h3>What Is Kafka Consumer Lag?</h3><p>Consumer lag is the difference between the latest message published to a partition (<strong>high-water mark offset</strong>) and the most recent message consumed (and committed) by a consumer group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*obnvsqTKlflldAA4Uu_DIA.png" /><figcaption><strong>If lag increases consistently, your consumers are struggling to keep up.</strong></figcaption></figure><h3>Why Consumer Lag Matters</h3><ul><li>📉 <strong>Increased Lag</strong> = delayed event processing</li><li>🧯 <strong>Data Loss Risk</strong>: if lag grows beyond topic retention, unprocessed data gets deleted</li><li>⚙️ <strong>System Bottlenecks</strong>: high lag can signal overloaded consumers, memory pressure, or poor design</li></ul><h4><strong>Root Causes of Consumer Lag</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*Q5FeUhZlJOJu0iQDQ-TxmA.png" /></figure><h4><strong>How to Monitor Consumer Lag</strong></h4><p>✅ <strong>Tools:</strong></p><ol><li>Kafka CLI:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*XHFs9E2ddA7yAj8ir2Gy4Q.png" /></figure><ol><li>Prometheus + JMX Exporter</li><li>AWS CloudWatch (for MSK):<br>* SumOffsetLag — total lag across all partitions<br>* MaxOffsetLag — highest lag among partitions</li></ol><p>✅ <strong>Monitoring Strategy:</strong></p><ol><li>Track per-partition lag for fine-grained visibility</li><li>Set alerts:<br> * If SumOffsetLag &gt; 100K for 5 minutes<br> * If MaxOffsetLag consistently increases</li></ol><h4><strong>Understanding Offsets: Core to Lag Management</strong></h4><p>Every message in Kafka has a unique <strong>offset</strong>. Kafka stores offsets <strong>per consumer group</strong>, not per consumer.</p><p>There are two types of offset commits:</p><ol><li><strong>Committed Offset</strong>: Last message acknowledged as processed</li><li><strong>Current Offset</strong>: Message being processed, but not yet committed</li></ol><p><strong>Offset Commit Strategies</strong></p><ol><li><strong>enable.auto.commit = true</strong><br>Kafka commits the latest offset periodically (default 5s)<br><strong>* Pros</strong>: Simple<br>* <strong>Cons</strong>: Risk of <strong>duplicate processing</strong> if crash occurs after processing but before commit</li><li><strong>commitSync() — Manual Sync Commit<br> </strong>consumer.commitSync();<br>* <strong>Safe</strong>: Ensures commit succeeded<br>* <strong>Use for</strong>: Critical checkpoints or shutdown hooks</li><li><strong>commitAsync() — Manual Async Commit<br> </strong>consumer.commitAsync((offsets, exception) -&gt; {<br> if (exception != null) log.error(“Commit failed”, exception);<br>});<br>* <strong>Faster</strong>: Doesn’t block the thread<br>* <strong>Use for</strong>: Continuous flow, combined with retries or fallback to commitSync()</li></ol><h4>Best Practice: Hybrid</h4><p>* Use commitAsync() during normal flow<br> * Use commitSync() on shutdown or rebalance</p><h3>What Happens During Rebalance?</h3><p>When Kafka adds/removes consumers or topics, it <strong>rebalances</strong> the group:</p><ul><li>Partitions are reassigned</li><li>If offsets are not committed, <strong>duplicate processing</strong> may occur</li></ul><p>Handle Rebalance Gracefully:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*Ms3u3jSpcV78hFmd7SZfUA.png" /></figure><h4>Tuning Kafka Consumers for Lag Reduction</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*ysKOcLzbmunTBiytuta45g.png" /></figure><h4><strong>Throughput Optimization Tips</strong></h4><p>* Match consumer count to partition count for parallelism<br>* Batch processing: process and commit offsets in batches<br>* Avoid blocking operations inside polling loop<br>* Use asynchronous or multi-threaded consumers carefully (Kafka clients are not thread-safe)</p><h4>Recovery: When Consumer Lag Grows Dangerously</h4><p>If lag grows and threatens data loss:</p><p>1. <strong>Scale Horizontally</strong><br>Add more consumers or processing threads</p><p>2. <strong>Optimize Logic</strong><br>Profile and reduce processing time per record</p><p>3.<strong> Increase Retention Temporarily</strong><br>Use this as a buffer while catching up</p><p>4. <strong>Reset Offsets (Last Resort):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*wC1IR4xhOq5sfQn1-9XSUA.png" /><figcaption><strong>Always deactivate consumers before doing this!</strong></figcaption></figure><h4>Real-Life Use Case: Fraud Detection Pipeline</h4><p>In a fraud detection system:</p><p>* Lag &gt; 10 seconds = stale transaction alerts<br> * Alert triggers on SumOffsetLag &gt; 1000<br>* During peak traffic, consumers autoscale via Kubernetes<br>* Offset commit strategy:</p><ul><li>commitAsync() per message</li><li>commitSync() during shutdown</li></ul><h4>Kafka Consumer Lag Management Checklist</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*iCZpM4gaZnT4hh5MpmRV0A.png" /></figure><p><strong>Conclusion: Turning Lag into Insight, and Insight into Action</strong></p><p><strong>Consumer lag is more than just a number — it’s a signal.</strong> It reflects the overall health of your Kafka pipeline, revealing how well your system handles offsets, resource allocation, and architectural robustness.</p><p>By proactively monitoring lag, applying smart commit strategies, and scaling consumers in line with actual demand, you can build real-time systems that are not only fast but also fault-tolerant and future-ready.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db28c20b7b31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[In-Depth Guide to Java 17 JVM: Architecture, Memory Model, Garbage Collection, Tuning & Monitoring]]></title>
            <link>https://medium.com/@priyankapruthe/in-depth-guide-to-java-17-jvm-architecture-memory-model-garbage-collection-tuning-monitoring-974c135eac3e?source=rss-95172fd0035f------2</link>
            <guid isPermaLink="false">https://medium.com/p/974c135eac3e</guid>
            <category><![CDATA[java-development]]></category>
            <category><![CDATA[java17]]></category>
            <category><![CDATA[jvmperformance]]></category>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[garbage-collection]]></category>
            <dc:creator><![CDATA[priyanka pruthi]]></dc:creator>
            <pubDate>Thu, 22 May 2025 12:42:55 GMT</pubDate>
            <atom:updated>2025-05-22T12:42:55.231Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jdqN6f0PW6UaePlk8Jd_EQ.png" /></figure><p>Java 17, a Long-Term Support (LTS) release, introduces stability and performance improvements while maintaining backward compatibility. At the heart of any Java program lies the <strong>Java Virtual Machine (JVM)</strong> — a powerful, platform-independent engine that executes bytecode, manages memory, and performs runtime optimizations.</p><p>This article provides a deep dive into the Java 17 JVM, covering its architecture, memory model, garbage collection strategies, performance tuning techniques, and monitoring practices for building scalable, production-grade applications.</p><h4>1. 🚀 What is the JVM?</h4><p>The <strong>Java Virtual Machine (JVM)</strong> is the cornerstone of the Java platform. It is an <strong>abstract computing machine</strong> that enables Java applications to run on any device or operating system without requiring changes to the source code. This <strong>Write Once, Run Anywhere (WORA)</strong> capability is achieved by compiling Java source code to <strong>bytecode</strong>, which the JVM executes.</p><p>Unlike traditional compilers that convert code directly to machine instructions for a specific CPU architecture, Java compiles to bytecode that the JVM interprets or compiles at runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*8GhzK_sMEOcLzAPZ2sohhA.png" /></figure><h4><strong><em>📦 Lifecycle of the JVM:</em></strong></h4><ul><li><strong>Class Loading</strong> via class loaders</li><li><strong>Bytecode Verification</strong> for safety</li><li><strong>Memory Allocation</strong> in heap and stack</li><li><strong>Execution</strong> via interpreter or JIT</li><li><strong>Garbage Collection</strong> for unused objects</li></ul><h4>☁️ <strong><em>JVM in Cloud and Containers:</em></strong></h4><p>Modern JVMs are <strong>cloud-aware</strong>, supporting:</p><ul><li>Containerized memory/resource limits</li><li>Fast startup (important for serverless)</li><li>Observability via Prometheus, JFR, etc.</li></ul><h4>📘 <strong><em>Types of JVM Implementations:</em></strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*J5XzHsTUaLeMhEHGK1M69w.png" /></figure><h4>🔐 <strong><em>JVM and Security:</em></strong></h4><p>The JVM protects execution using</p><ul><li>Bytecode verification</li><li>ClassLoader isolation</li><li>SecurityManager &amp; policy files</li><li>Sandboxing (legacy for applets)</li></ul><h4>2. 🏗️ JVM Architecture and Components</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*z9TfQaNlj_XA2erhh5UI5A.png" /></figure><h4>ClassLoader Types:</h4><ul><li><strong>Bootstrap ClassLoader</strong> — Loads core Java classes.</li><li><strong>Extension ClassLoader</strong> — Loads JDK extension classes.</li><li><strong>Application ClassLoader</strong> — Loads user-defined classes.</li><li><strong>Custom ClassLoaders</strong> — Used in frameworks, containers, and OSGi.</li></ul><h4>3. 🧠 JVM Memory Model in Java 17</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*jVttkzO1ELXbZ17hpiRrKw.png" /></figure><h4>Heap Structure:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*Q21CyFuY2nSTad0Oz1m2tg.png" /></figure><ul><li><strong>Eden</strong>: New objects are allocated here.</li><li><strong>Survivor</strong>: Short-lived objects moved between S0 and S1.</li><li><strong>Old Gen</strong>: Long-lived objects after multiple GC cycles.</li></ul><h4>4. ⚙️ Execution Engine and JIT Compiler</h4><h4>Execution Process:</h4><ul><li>Load class via ClassLoader.</li><li>Interpret bytecode initially.</li><li>Use JIT compiler to optimize hot code paths.</li></ul><p>JIT Compiler Types:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*9CA2CkkO3NOU9vHGj6wbWg.png" /></figure><p>Optimization<br>The Just-In-Time (JIT) compiler in the JVM performs several advanced optimizations to improve the runtime performance of Java applications. These optimizations aim to reduce the amount of work the CPU must do and to maximize efficient use of memory and processor resources.</p><p>1. <strong>Inlining</strong></p><p>Inlining is the process where the JVM replaces a method call with the actual method body during compilation. By doing this, the JVM eliminates the overhead of the method call (such as stack frame creation and return address bookkeeping). Inlining is especially effective for small, frequently called methods (like getters/setters or utility functions).</p><p><strong>Benefits:</strong></p><ul><li>Reduces method call overhead.</li><li>Enables further optimizations such as constant propagation and dead code elimination because the compiler can see the combined code.</li><li><strong>Example:</strong><br> Instead of calling int result = calculateSum(a, b);, the JVM replaces the call with int result = a + b; directly.</li></ul><p>2.<strong> Loop Unrolling</strong></p><p>Loop unrolling is a technique where the JVM expands the loop body multiple times within a single iteration, reducing the overhead of loop control code (like incrementing counters and checking termination conditions).</p><p><strong>Benefits:</strong></p><ul><li>Decreases the number of branch instructions executed.</li><li>Allows more instruction-level parallelism, improving CPU pipeline utilization.</li><li>Can improve cache locality by reducing branching.</li><li><strong>Example:</strong><br> Instead of running a loop 10 times doing sum += array[i];, the JVM might transform it to run 5 iterations with two additions each, cutting down loop overhead.</li></ul><p>3. <strong>Dead Code Elimination</strong></p><p>Dead code elimination removes instructions and code blocks that do not affect the program’s observable behavior. This can include unused variables, code after a return statement, or branches that never execute due to known conditions.</p><p><strong>Benefits:</strong></p><ul><li>Reduces the size of generated machine code.</li><li>Improves execution speed by avoiding unnecessary instructions.</li><li>Saves memory and CPU cycles.</li><li><strong>Example:</strong><br> If the JVM detects a block of code inside an if (false) condition or after a return statement, it removes that code entirely.</li></ul><p>4<strong>. Escape Analysis</strong></p><p>Escape analysis determines whether an object is accessible outside the method or thread in which it was created. If the JVM determines that an object does <strong>not escape</strong>, it can perform special optimizations like allocating the object on the stack instead of the heap or even eliminating the allocation altogether.</p><ul><li><strong>Benefits:</strong></li><li>Reduces pressure on the heap and garbage collector, as fewer objects need to be heap-allocated.</li><li>Improves performance by avoiding expensive heap allocation and GC overhead.</li><li><strong>Example:</strong><br> An object created inside a method and used only within that method (and thread) may be allocated on the stack, making its creation and destruction very cheap.</li></ul><h4>5. ♻️ Garbage Collection in Java 17</h4><p>Garbage Collection (GC) is one of the JVM’s most critical responsibilities, responsible for <strong>automatic memory management</strong> by identifying and reclaiming memory occupied by objects that are no longer reachable by the application. GC helps prevent memory leaks and optimizes resource usage, thereby enabling high application throughput and reliability without manual intervention.</p><h4><strong>How Garbage Collection Works:</strong></h4><p>At a high level, GC performs the following:</p><ol><li><strong>Identify live objects:</strong> Objects still reachable via references from thread stacks, static fields, or other live objects.</li><li><strong>Mark phase:</strong> Traverses object graph starting from roots and marks reachable objects.</li><li><strong>Sweep phase:</strong> Reclaims memory of unmarked (unreachable) objects.</li><li><strong>Compact phase:</strong> Optionally, moves objects to reduce fragmentation and improve allocation performance.</li></ol><h4>Why GC is Important:</h4><ul><li>Prevents <strong>memory leaks</strong> by reclaiming unused objects.</li><li>Ensures efficient use of limited memory resources.</li><li>Frees developers from manual memory management errors like dangling pointers or double frees, which are common in languages like C/C++.</li></ul><h4><strong>JVM Heap &amp; Generations:</strong></h4><p>The heap is split into multiple <strong>generations</strong> to optimize GC performance based on object lifespan:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*TyurxtiaX_ag5bzXov-DlA.png" /></figure><h4>Types of Garbage Collectors in Java 17</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*78gqGjy5x5CDxkUIYgQfkA.png" /></figure><h4>Garbage Collection Phases Detailed:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*QwoL2aJf6FC5UjBmXwO21Q.png" /></figure><p><strong>How Generational GC Works:</strong></p><p>Generational GC leverages the observation that <strong>most objects die young</strong>:</p><ul><li>Objects start in <strong>Eden</strong> (Young Gen).</li><li>Surviving objects move to <strong>Survivor spaces</strong> (S0/S1).</li><li>After surviving multiple GC cycles, objects are promoted to the <strong>Old Generation</strong>.</li></ul><p>Minor GCs focus only on Young Gen, which are fast and frequent. Full GCs clean Old Gen and are more expensive.</p><h4>GC Metrics to Monitor:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*Lrxbm271UUiZ24_3HZgBaA.png" /></figure><h4>6. 📈 Choosing the Right Garbage Collector</h4><p>Choosing a GC depends on your application’s memory usage, latency, and throughput requirements:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AVQuwSxsSmDX9AbmZt7kkw.png" /></figure><h4>Tips:</h4><ul><li><em>Use </em><strong><em>G1 GC</em></strong><em> for most modern applications needing a balance of latency and throughput.</em></li><li><em>Consider </em><strong><em>ZGC</em></strong><em> or </em><strong><em>Shenandoah</em></strong><em> if you have very large heaps (&gt;16 GB) and require low pause times.</em></li><li><em>Always analyze your application’s behavior and monitor GC metrics before switching collectors.</em></li></ul><h4>7. 🔧 JVM Tuning Techniques</h4><p>JVM tuning can significantly improve app performance. Always <strong>monitor before tuning</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*_qo4zrpKrlZ9VpL7M-emtA.png" /></figure><h3>Sample Tuning Profiles:</h3><p><strong>Dev Environment:</strong></p><pre>-Xms256m -Xmx512m -XX:+UseG1GC</pre><p><strong>Production — Large App:</strong></p><pre>-Xms4g -Xmx8g -XX:+UseZGC -XX:+HeapDumpOnOutOfMemoryError</pre><h4>Tips:</h4><ul><li>Use -XX:+PrintFlagsFinal to see active JVM flags.</li><li>Avoid overprovisioning heap; large heaps can increase GC pause time.</li></ul><h4>8. 🔍 JVM Monitoring and Diagnostics</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*xZTNRMFl-hgi60RAvq6guQ.png" /></figure><h4>Sample Commands:</h4><pre>jstat -gc &lt;pid&gt; 1000<br>jcmd &lt;pid&gt; GC.heap_info<br>jmap -heap &lt;pid&gt;</pre><p>9. 🛠 Real-World Tuning &amp; Monitoring Case Study</p><p><strong>Scenario:</strong></p><p>A Spring Boot microservice deployed on Kubernetes exhibited random GC pauses &gt;1s.</p><p><strong>Diagnosis:</strong></p><ul><li>G1 GC used, but MaxGCPauseMillis was not configured.</li><li>GC logs showed full GC triggered frequently.</li></ul><p><strong>Fix:</strong></p><pre>-XX:+UseG1GC -XX:MaxGCPauseMillis=100 -Xms4g -Xmx4g</pre><h4>Result:</h4><p>GC pause times dropped below 200ms with stable throughput.</p><h4>✅ Conclusion</h4><p>Java 17’s JVM is a powerful, production-grade runtime that provides rich capabilities for memory management, multithreading, performance tuning, and monitoring. Whether building microservices, batch jobs, or monoliths, understanding the internals of the JVM enables developers and architects to build <strong>resilient, scalable, and performant applications</strong>.</p><blockquote><em>🔁 </em><strong><em>Always follow the cycle: Monitor → Diagnose → Tune → Monitor again.</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=974c135eac3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java 21’s Virtual Threads: The Secret to Handling Millions of Concurrent Requests]]></title>
            <link>https://medium.com/@priyankapruthe/java-21s-virtual-threads-the-secret-to-handling-millions-of-concurrent-requests-29f10d71c5f4?source=rss-95172fd0035f------2</link>
            <guid isPermaLink="false">https://medium.com/p/29f10d71c5f4</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[java-21-features]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[virtual-threads]]></category>
            <dc:creator><![CDATA[priyanka pruthi]]></dc:creator>
            <pubDate>Wed, 19 Feb 2025 06:40:30 GMT</pubDate>
            <atom:updated>2025-02-19T06:40:30.952Z</atom:updated>
            <content:encoded><![CDATA[<p>Dive into the world of lightweight, high-performance concurrency in Java 21 using Virtual Threads.</p><p>Concurrency has always been a challenging problem for developers, especially when handling thousands or millions of tasks simultaneously. Traditional solutions, such as thread pools, can be inefficient and resource-intensive. With the introduction of <strong>Virtual Threads</strong> in Java 21 (as part of Project Loom), there’s a powerful new option for developers looking to scale their applications and simplify concurrency management.</p><h3>What Are Project Loom?</h3><p>Project Loom is an OpenJDK initiative aimed at bringing a lightweight concurrency framework to the Java platform. It enhances the Java Thread API, enabling it to support applications that require massive concurrency. By decoupling Java threads from operating system threads, Project Loom allows for more efficient handling of thousands or even millions of concurrent tasks.</p><h3>What Are Virtual Threads?</h3><p>Virtual threads, introduced in Java 21, are lightweight threads managed by the Java Virtual Machine (JVM) rather than the operating system. This enables applications to scale effortlessly by creating and managing millions of virtual threads with minimal overhead.</p><p>Unlike traditional threads, which require significant memory for their stacks and are scheduled by the operating system, virtual threads are optimized for efficiency. They consume only a fraction of the resources, enabling Java to handle thousands or even millions of concurrent tasks.</p><h3>Key Benefits of Virtual Threads</h3><p>Virtual threads offer several key advantages that make them a game-changer for high-concurrency applications:</p><ul><li><strong>Scalability</strong>: Virtual threads allow you to scale applications seamlessly. You can create millions of virtual threads without worrying about running into memory or resource limits.</li><li><strong>Reduced Memory Footprint</strong>: While traditional threads consume hundreds of kilobytes of memory each, virtual threads only require a few kilobytes, making them significantly more memory-efficient.</li><li><strong>Efficient Context Switching</strong>: Unlike traditional threads, which require expensive context switching at the OS level, virtual threads are scheduled by the JVM with minimal overhead. This reduces the performance cost of switching between tasks.</li><li><strong>Simplified Concurrency</strong>: With virtual threads, developers can handle high-concurrency workloads in a much simpler way. Tasks can be written in a blocking style without the need for complex callback-based code, which is common in asynchronous programming.</li></ul><h3>How Virtual Threads Work</h3><p>The JVM schedules virtual threads in a way that minimizes the cost of creating and switching between threads. Here’s a simplified overview of their lifecycle:</p><ol><li><strong>Creation</strong>: Virtual threads are created using the Thread.ofVirtual().start() API. Unlike traditional threads, creating a virtual thread is fast and requires minimal resources.</li><li><strong>Execution</strong>: Once created, virtual threads execute tasks just like traditional threads. However, since they are lightweight, you can create and execute millions of them simultaneously without running into memory issues.</li><li><strong>Blocking</strong>: Virtual threads are particularly useful for I/O-bound tasks (like waiting for data from a database or making an HTTP request). When a virtual thread blocks (e.g., waiting for an I/O operation), it doesn’t consume unnecessary resources. Other tasks can continue to run without delay.</li><li><strong>Completion</strong>: Once a task is completed, the virtual thread terminates. The JVM handles cleanup, making virtual threads much easier to manage compared to traditional threads, which require more manual handling of thread lifecycles.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*FjQa1ze3uiQ1RVv8SlbtSw.png" /><figcaption>Virtual Thread Life Cycle</figcaption></figure><h3>Traditional Threads vs. Virtual Threads</h3><p>Let’s explore the key differences between traditional threads and virtual threads, which can help you understand when to use one over the other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*KJno0zAsGMY6GkqCwUCj4g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Py52sIAJd-b50JCgMS3w8Q.png" /></figure><p>As you can see, virtual threads offer advantages when scalability and memory efficiency are crucial — particularly for applications that involve many I/O-bound tasks.</p><h3>Case Study: Solving High-Concurrency Problems in a Web API Gateway</h3><p>Let’s consider a real-world example of a <strong>high-traffic API gateway</strong> in a microservices architecture. This system processes hundreds of thousands — or even millions — of requests per second. Imagine this gateway is responsible for serving real-time weather data via an API.</p><h4>Challenges with Traditional Threads:</h4><ol><li><strong>High Memory Usage</strong>: The system was overwhelmed by the number of threads required to handle incoming requests. Each request was mapped to a traditional thread, leading to high memory consumption.</li><li><strong>Limited Scalability</strong>: As the number of requests grew, the thread pool became exhausted, leading to increased latency and even failure to process new requests.</li><li><strong>Blocking I/O Operations</strong>: Many of the requests involved waiting for external data sources (e.g., calling a weather service or querying a database). These blocking operations consumed valuable threads, leading to resource starvation and poor performance.</li></ol><h4>How Virtual Threads Solve These Problems:</h4><p>With virtual threads, the API gateway was able to handle <strong>millions of concurrent requests</strong> more efficiently, significantly improving the system’s scalability and reducing memory usage.</p><ul><li><strong>Scalability</strong>: Virtual threads made it possible to scale the gateway to handle up to 10 million concurrent requests without hitting memory constraints or exhausting the thread pool. Each request could be handled by its own virtual thread, without worrying about running out of threads or memory.</li><li><strong>Reduced Memory Footprint</strong>: Virtual threads use much less memory than traditional threads. This enabled the API gateway to scale horizontally without requiring more hardware resources.</li><li><strong>Efficient Handling of Blocking I/O</strong>: When making external calls (such as querying weather data), virtual threads could block without consuming CPU resources. This allowed the system to handle more requests simultaneously without performance degradation.</li></ul><h4>Real-World Results:</h4><p>After refactoring the API gateway to use virtual threads, the company experienced significant improvements:</p><ul><li><strong>Scalability</strong>: The system now handled up to 10 million requests per second, a 200x increase over what was possible with traditional threads.</li><li><strong>Reduced Latency</strong>: By efficiently handling blocking I/O operations, the system reduced average response times by 40%.</li><li><strong>Lower Infrastructure Costs</strong>: With virtual threads, the company reduced their infrastructure costs by 30%, as they were able to serve more requests with fewer physical servers.</li></ul><h3>Code Example: Creating Virtual Threads</h3><p>Here’s a simple example of how to create and use virtual threads in Java to handle concurrent requests in the weather API system:</p><pre>import java.util.concurrent.*;<br><br>public class VirtualThreadAPI {<br>    public static void main(String[] args) {<br>        Runnable requestTask = () -&gt; {<br>            try {<br>                // Simulate an I/O operation (e.g., calling a weather service)<br>                System.out.println(&quot;Processing request on &quot; + Thread.currentThread().getName());<br>                Thread.sleep(500);  // Simulate I/O delay<br>                System.out.println(&quot;Request completed on &quot; + Thread.currentThread().getName());<br>            } catch (InterruptedException e) {<br>                Thread.currentThread().interrupt();<br>            }<br>        };<br>        // Create a pool of virtual threads to handle incoming requests<br>        ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor();<br>        // Simulate multiple requests being processed concurrently<br>        for (int i = 0; i &lt; 1000; i++) {<br>            executorService.submit(requestTask);<br>        }<br>        // Shutdown executor<br>        executorService.shutdown();<br>    }<br>}</pre><p>In this example, the ExecutorService creates a pool of virtual threads that handle incoming requests. Each request is processed on its own virtual thread, allowing the system to handle a large number of concurrent tasks with minimal memory usage.</p><h3>Memory Footprint: Virtual Threads vs. Traditional Threads</h3><p>Memory consumption is one of the most significant benefits of virtual threads. Traditional threads can consume anywhere from 100 KB to 1 MB of memory each, depending on the operating system. Virtual threads, however, only require about 1 KB to 2 KB of memory per thread, making them far more efficient, especially when handling large numbers of tasks.</p><p>For example:</p><ul><li><strong>Traditional Threads</strong>: A system using 1,000 traditional threads might require 100 MB of memory.</li><li><strong>Virtual Threads</strong>: The same system using virtual threads might only require 2 MB of memory, allowing for more efficient use of resources.</li></ul><h3>Potential Pitfalls and Trade-offs</h3><p>While virtual threads offer significant benefits, they are not a one-size-fits-all solution. Here are a few trade-offs to consider:</p><ul><li><strong>Not Ideal for CPU-bound Tasks</strong>: Virtual threads excel in I/O-bound tasks, but for CPU-heavy operations, traditional threads may still be more efficient.</li><li><strong>JVM Overhead</strong>: The JVM schedules virtual threads, which means there is some overhead associated with this management. However, this overhead is minimal compared to the cost of managing OS-level threads.</li><li><strong>Debugging and Monitoring</strong>: Virtual threads may require updated debugging and monitoring tools, as they are managed by the JVM. It’s important to ensure your development and operations environment is compatible with virtual threads.</li></ul><h3>Conclusion: Why Choose Virtual Threads?</h3><p>Java 21’s <strong>Virtual Threads</strong> are a powerful tool for developers looking to scale their applications without sacrificing performance or efficiency. By providing a lightweight, low-cost alternative to traditional threads, virtual threads simplify the development of high-concurrency systems, especially for I/O-bound tasks like web servers and microservices.</p><p>In the <strong>case study</strong> of the high-traffic API gateway, we saw how virtual threads allowed the system to handle millions of concurrent requests with minimal memory usage, faster response times, and lower infrastructure costs. For developers building high-concurrency systems, virtual threads are a must-try.</p><p><strong>Ready to scale your applications with virtual threads?</strong> Start by refactoring your existing systems or experimenting with virtual threads in your next project. With Java 21, scaling your applications has never been easier!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29f10d71c5f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Java 8: Functional Interfaces, Streams, and Optional]]></title>
            <link>https://medium.com/@priyankapruthe/mastering-java-8-functional-interfaces-streams-and-optionals-cb549ac6cb82?source=rss-95172fd0035f------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb549ac6cb82</guid>
            <category><![CDATA[stream]]></category>
            <category><![CDATA[java8-streams]]></category>
            <category><![CDATA[java-8-feature]]></category>
            <category><![CDATA[optionals]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[priyanka pruthi]]></dc:creator>
            <pubDate>Mon, 10 Feb 2025 13:49:13 GMT</pubDate>
            <atom:updated>2025-02-19T06:37:55.669Z</atom:updated>
            <content:encoded><![CDATA[<p>Java 8 Functional programming concepts</p><p>With the introduction of <strong>Java 8</strong>, the language embraced <strong>functional programming</strong> concepts that were long available in other languages. Java developers gained new tools like <strong>Functional Interfaces</strong>, <strong>Streams</strong>, and <strong>Optionals</strong>, allowing for more concise, readable, and expressive code. This article will take you through these concepts, from simple examples to advanced use cases, ensuring you have a solid grasp of Java 8’s functional capabilities.</p><h3>Functional Interfaces: The Backbone of Java 8’s Functional Programming</h3><p>In Java 8, a <strong>Functional Interface</strong> is an interface with <strong>exactly one abstract method</strong>. They are the core of functional programming in Java and can be used with lambda expressions to implement behavior in a flexible way.</p><h3>Basic Example: Simple Functional Interface</h3><pre>@FunctionalInterface<br>public interface Greeter {<br>    void greet(String name);<br>}<br><br>public class FunctionalInterfaceExample {<br>    public static void main(String[] args) {<br>        Greeter greeter = (name) -&gt; System.out.println(&quot;Hello, &quot; + name);<br>        greeter.greet(&quot;John&quot;);<br>    }<br>}</pre><p><strong>Explanation</strong>:<br>Here, we created a simple <strong>Functional Interface</strong> called Greeter with a single method greet(). We then implemented it using a lambda expression. This is the heart of functional programming in Java—simplifying code with anonymous methods.</p><h3>Advanced Example: Composing Functions</h3><p>Java 8 provides several methods in the Function interface to compose functions and chain them together. You can combine multiple simple operations into one.</p><pre>import java.util.function.Function;<br>public class FunctionCompositionExample {<br>    public static void main(String[] args) {<br>        Function&lt;Integer, Integer&gt; add5 = x -&gt; x + 5;<br>        Function&lt;Integer, Integer&gt; multiplyBy2 = x -&gt; x * 2;<br>        Function&lt;Integer, Integer&gt; addThenMultiply = add5.andThen(multiplyBy2);<br>        Function&lt;Integer, Integer&gt; multiplyThenAdd = add5.compose(multiplyBy2);<br>        System.out.println(&quot;addThenMultiply(3): &quot; + addThenMultiply.apply(3)); // 16<br>        System.out.println(&quot;multiplyThenAdd(3): &quot; + multiplyThenAdd.apply(3)); // 11<br>    }<br>}</pre><p><strong>Explanation</strong>:</p><ul><li><strong>andThen()</strong> applies multiplyBy2 after add5.</li><li><strong>compose()</strong> applies add5 after multiplyBy2.<br>This is a powerful way to compose complex operations by chaining simpler functions.</li></ul><h3>Streams: A New Way of Handling Collections</h3><p>Java 8 introduced <strong>Streams</strong> to process sequences of elements in a declarative manner. Streams allow for efficient, parallelizable operations on collections with minimal verbosity.</p><h3>Basic Stream Operations</h3><pre>import java.util.*;<br>import java.util.stream.*;<br><br>public class StreamBasicExample {<br>    public static void main(String[] args) {<br>        List&lt;Integer&gt; numbers = Arrays.asList(1, 2, 3, 4, 5);<br>        // Filtering and printing even numbers<br>        numbers.stream()<br>                .filter(n -&gt; n % 2 == 0)<br>                .forEach(System.out::println);<br>    }<br>}</pre><p><strong>Explanation</strong>:</p><ul><li><strong>filter()</strong> is an intermediate operation that returns a new stream with only the even numbers.</li><li><strong>forEach()</strong> is a terminal operation that consumes the stream and prints the result.</li></ul><h3>Intermediate and Terminal Operations</h3><p><strong>Intermediate Operations</strong> return a new stream and are <strong>lazy</strong> in nature, meaning they don’t process the data until a terminal operation is invoked.</p><ul><li><strong>map()</strong>: Transforms each element.</li><li><strong>filter()</strong>: Filters out elements as per the condition.</li><li><strong>sorted()</strong>: Sorts elements.</li></ul><p><strong>Terminal Operations</strong> are eager and trigger the processing of the stream. They include <strong>collect()</strong>, <strong>reduce()</strong>, and <strong>forEach()</strong>.</p><pre>import java.util.*;<br>import java.util.stream.*;<br><br>public class StreamAdvancedExample {<br>    public static void main(String[] args) {<br>        List&lt;String&gt; words = Arrays.asList(&quot;apple&quot;, &quot;banana&quot;, &quot;orange&quot;, &quot;grape&quot;);<br>        // Intermediate: map and filter<br>        long count = words.stream()<br>                .filter(word -&gt; word.length() &gt; 5)      // Filter long words<br>                .map(String::toUpperCase)               // Convert to uppercase<br>                .distinct()                             // Remove duplicates<br>                .count();                               // Terminal operation<br>        System.out.println(&quot;Count of distinct long words: &quot; + count);<br>    }<br>}</pre><p><strong>Explanation</strong>:</p><ul><li>The <strong>filter()</strong> method removes words that are shorter than 6 characters.</li><li><strong>map()</strong> converts the remaining words to uppercase.</li><li><strong>distinct()</strong> eliminates duplicate entries.</li><li><strong>count()</strong> is the terminal operation that counts the resulting elements.</li></ul><h3>Parallel Streams and Performance</h3><p>Parallel streams are great for handling large datasets by splitting the work across multiple CPU cores. However, they come with overhead and are not always faster for small data sets.</p><pre>import java.util.*;<br>import java.util.stream.*;<br>import java.time.*;<br><br>public class ParallelStreamExample {<br>    public static void main(String[] args) {<br>        List&lt;Integer&gt; numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);<br>        long start = System.nanoTime();<br>        int sum = numbers.parallelStream()<br>                         .filter(n -&gt; n % 2 == 0)<br>                         .map(n -&gt; n * n)<br>                         .reduce(0, Integer::sum);<br>        long end = System.nanoTime();<br>        System.out.println(&quot;Parallel stream sum: &quot; + sum);<br>        System.out.println(&quot;Time taken: &quot; + (end - start) + &quot; ns&quot;);<br>    }<br>}</pre><p><strong>Explanation</strong>:</p><ul><li><strong>parallelStream()</strong> enables multi-threaded processing.</li><li>The <strong>performance</strong> comparison between parallel and sequential streams would depend on the size and complexity of the data.</li></ul><h3>Performance Considerations:</h3><ul><li><strong>Overhead</strong>: For small datasets, the overhead of managing multiple threads can outweigh the benefits.</li><li><strong>Stateful Operations</strong>: Be cautious with operations like distinct() and sorted() in parallel streams, as they can lead to inefficiency or unexpected results.</li></ul><p><strong>Real-World Example:</strong><br>If you’re processing a large collection of log files, using <strong>parallel streams</strong> can significantly speed up the operation since reading files, filtering, and transforming can be done concurrently.</p><h3>Optionals: Safe Handling of Nulls</h3><p>The <strong>Optional</strong> class in Java 8 allows developers to avoid null-related issues by encapsulating the possibility of a missing value.</p><h3>Basic Example: Creating and Using Optionals</h3><pre>import java.util.*;<br><br>public class OptionalExample {<br>    public static void main(String[] args) {<br>        Optional&lt;String&gt; name = Optional.ofNullable(&quot;John&quot;);<br>        // Checking if value is present<br>        name.ifPresent(n -&gt; System.out.println(&quot;Hello, &quot; + n));<br>    }<br>}</pre><p><strong>Explanation</strong>:<br>Here, <strong>Optional.ofNullable()</strong> creates an optional that may or may not contain a value. <strong>ifPresent()</strong> only executes if the value is present, preventing NullPointerException.</p><h3>Chaining and Combining Optionals</h3><p>Java 8 allows for chaining multiple transformations on <strong>Optionals</strong> using <strong>map()</strong> and <strong>flatMap()</strong>. This enables a safe and functional approach to handling <strong>null</strong> values.</p><pre>import java.util.Optional;<br><br>public class OptionalChainingExample {<br>    public static void main(String[] args) {<br>        Optional&lt;String&gt; name = Optional.of(&quot;John&quot;);<br>        Optional&lt;String&gt; upperCaseName = name<br>                .map(String::toUpperCase)<br>                .filter(n -&gt; n.startsWith(&quot;J&quot;));<br>        upperCaseName.ifPresent(System.out::println);  // Output: JOHN<br>    }<br>}</pre><p><strong>Explanation</strong>:</p><ul><li><strong>map()</strong> transforms the value to uppercase.</li><li><strong>filter()</strong> ensures that the name starts with &quot;J&quot;.</li></ul><h3>Combining Multiple Optionals</h3><p><strong>flatMap()</strong> is useful when you need to combine multiple Optionals.</p><pre>import java.util.Optional;<br><br>public class OptionalCombinationExample {<br>    public static void main(String[] args) {<br>        Optional&lt;String&gt; name = Optional.of(&quot;John&quot;);<br>        // Combining Optionals<br>        Optional&lt;Integer&gt; nameLength = name.flatMap(n -&gt; Optional.of(n.length()));<br>        <br>        nameLength.ifPresent(System.out::println);  // Output: 4<br>    }<br>}</pre><p><strong>Explanation</strong>:<br><strong>flatMap()</strong> allows for mapping an Optional&lt;String&gt; into another Optional&lt;Integer&gt;.</p><h3>Advanced Streams: Custom Collectors</h3><p>Java 8’s <strong>Collectors API</strong> allows you to define custom collection strategies, making stream processing even more flexible.</p><h3>Custom Collector Example: Grouping by Multiple Criteria</h3><pre>import java.util.*;<br>import java.util.stream.*;<br><br>public class CustomCollectorExample {<br>    public static void main(String[] args) {<br>        List&lt;String&gt; words = Arrays.asList(&quot;apple&quot;, &quot;banana&quot;, &quot;orange&quot;, &quot;grape&quot;);<br>        // Group words by their length<br>        Map&lt;Integer, List&lt;String&gt;&gt; groupedByLength = words.stream()<br>                .collect(Collectors.groupingBy(String::length));<br>        System.out.println(groupedByLength);<br>    }<br>}</pre><p><strong>Explanation</strong>:<br>We’re using <strong>groupingBy()</strong> to group words by their length.</p><h3>Real-World Use Case: Grouping and Partitioning Data</h3><pre>import java.util.*;<br>import java.util.stream.*;<br><br>public class PartitioningExample {<br>    public static void main(String[] args) {<br>        List&lt;String&gt; words = Arrays.asList(&quot;apple&quot;, &quot;banana&quot;, &quot;orange&quot;, &quot;grape&quot;);<br>        // Partition words into long and short ones<br>        Map&lt;Boolean, List&lt;String&gt;&gt; partitioned = words.stream()<br>                .collect(Collectors.partitioningBy(word -&gt; word.length() &gt; 5));<br>        System.out.println(partitioned);<br>    }<br>}</pre><p><strong>Explanation</strong>:<br>We use <strong>partitioningBy()</strong> to divide the words into two categories: long and short.</p><h3>Conclusion: Power and Flexibility of Java 8 Features</h3><p>By mastering <strong>Functional Interfaces</strong>, <strong>Streams</strong>, and <strong>Optionals</strong>, you unlock the full potential of Java 8’s functional programming capabilities.</p><h3>Key Takeaways:</h3><ul><li><strong>Functional Interfaces</strong> simplify code by allowing behavior to be passed around as arguments.</li><li><strong>Streams</strong> enable concise, parallelizable operations on data with minimal boilerplate.</li><li><strong>Optionals</strong> prevent null-related errors and make code more readable and safe.</li></ul><h3>Advanced Insights:</h3><ul><li><strong>Parallel Streams</strong>: Use them when processing large data sets, but be cautious about their overhead.</li><li><strong>Composing Functions</strong>: Allows for cleaner, reusable, and modular code.</li><li><strong>Custom Collectors</strong>: Provide flexibility in how you collect and group data, making your stream operations more powerful.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb549ac6cb82" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Java Architecture: Critical Skills]]></title>
            <link>https://medium.com/@priyankapruthe/mastering-java-architecture-20-critical-skills-ecb94bec658b?source=rss-95172fd0035f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecb94bec658b</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[java-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[priyanka pruthi]]></dc:creator>
            <pubDate>Fri, 31 Jan 2025 09:10:52 GMT</pubDate>
            <atom:updated>2025-01-31T10:50:29.399Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*YdK2r4z1Mk7_b9Rr.jpg" /><figcaption>Pic Courtesy : <a href="https://www.dreamstime.com/">https://www.dreamstime.com/</a></figcaption></figure><p>As the software development landscape continues to evolve, Java remains a foundational language that powers a vast array of applications globally. In 2025, the role of a Java software architect is more significant than ever. Architects must possess a deep understanding of Java and its ecosystem, while staying updated with the latest trends, technologies, and best practices. This ensures the creation of scalable, resilient, and high-performing applications.</p><p>This article outlines the key areas every Java software architect should focus on mastering in 2025. Covering diverse topics such as microservices, cloud-native applications, reactive programming, and blockchain, these areas represent the essential knowledge for navigating the ever-changing software architecture space. Additionally, relevant books, resources, and YouTube training links are recommended for each topic, offering a comprehensive guide to keep pace with these emerging technologies.</p><h3>1. Microservices Architecture</h3><p>Microservices architecture involves breaking down an application into smaller, independently deployable services that are loosely coupled. This approach allows for easier scaling, development, and maintenance. Mastery of this architecture is essential for building modern, resilient systems.</p><h4>Related Technologies</h4><ul><li><strong>Spring Boot:</strong> A framework for building stand-alone, production-grade Spring applications.</li><li><strong>Quarkus:</strong> Optimized for Kubernetes, it provides fast startup times and a low memory footprint.</li><li><strong>OpenShift:</strong> A Kubernetes-based platform to manage and deploy containerized applications.</li></ul><h4>Recommended Books</h4><ul><li>“Building Microservices: Designing Fine-Grained Systems” by Sam Newman</li><li>“Spring Microservices in Action” by John Carnell</li><li>“Quarkus Cookbook: Kubernetes-Native Java” by Alex Soto Bueno and Jason Porter</li></ul><h4>YouTube Training Links</h4><ul><li><a href="https://www.youtube.com/watch?v=BLlEgtp2_i8">Spring Boot Microservices Tutoria</a>l</li><li><a href="https://www.youtube.com/watch?v=VvEUWsrx5yw&amp;list=PL5CmOIMMdhxOYct7-RsGmdsm4IBhb4lSZ">Quarkus Full Course for Beginners</a></li></ul><h3>2. Cloud-Native Applications</h3><p>Designing applications that leverage cloud platforms is essential for achieving scalability, reliability, and operational efficiency. Cloud-native architecture allows organizations to optimize resource usage and improve agility.</p><h4>Related Technologies</h4><ul><li><strong>AWS (Amazon Web Services):</strong> Comprehensive cloud services for computing, storage, and application deployment.</li><li><strong>Google Cloud Platform:</strong> Offers services for scalable applications, storage, and analytics.</li><li><strong>Microsoft Azure:</strong> Provides tools for managing cloud infrastructure and developing cloud-based applications.</li></ul><h4>Recommended Books</h4><ul><li>“Cloud Native Java” by Josh Long and Kenny Bastani</li></ul><h4>YouTube Training Links</h4><ul><li><a href="https://www.youtube.com/watch?v=Ia-UEYYR44s">AWS Cloud Developer — Full Course for Beginners</a></li><li><a href="https://www.youtube.com/watch?v=fZOz13joN0o">Google Cloud Platfor</a>m</li><li><a href="https://www.youtube.com/watch?v=5abffC-K40c">Azure Cloud </a>Fundamental</li></ul><h3>3. Containerization and Orchestration</h3><p>Containerization ensures applications run consistently across various environments, while orchestration tools simplify managing multiple containers. These practices are essential for modern application development, especially in microservices architectures.</p><h4>Related Technologies</h4><ul><li><strong>Docker:</strong> Enables packaging and running applications in containers.</li><li><strong>Kubernetes:</strong> An open-source system for automating the deployment and management of containerized applications.</li><li><strong>OpenShift:</strong> Extends Kubernetes with DevOps tools to enhance container orchestration.</li></ul><h4>Recommended Books</h4><ul><li>“Docker: Up &amp; Running” by Karl Matthias and Sean P. Kane</li><li>“Kubernetes Up &amp; Running” by Kelsey Hightower, Brendan Burns, and Joe Beda</li></ul><h4>YouTube Training Links</h4><ul><li><a href="https://www.youtube.com/watch?v=pTFZFxd4hOI">Docker for Beginners — Docker Official</a></li><li><a href="https://www.youtube.com/watch?v=X48VuDVv0do">Kubernetes Tutorial for Beginners — TechWorld with Nana</a></li><li><a href="https://www.youtube.com/watch?v=ex9l_EBMMHs&amp;list=PLH5uDiXcw8tRG7_RJOe7leEvDBfC46Bl_">OpenShift for Developers — Red Hat OpenShift</a></li></ul><h3>4. Reactive Programming</h3><p>Reactive programming is essential for handling asynchronous data streams, a key element in modern web applications and real-time systems.</p><h4>Related Technologies</h4><ul><li><strong>Project Reactor:</strong> A core library for building reactive applications on the JVM.</li><li><strong>Akka:</strong> A toolkit for building concurrent, distributed, and resilient systems.</li><li><strong>RxJava:</strong> A library for composing asynchronous and event-based programs.</li></ul><h4>Recommended Books</h4><ul><li>“Reactive Programming with RxJava” by Tomasz Nurkiewicz and Ben Christensen</li><li>“Reactive Spring” by Josh Long</li></ul><h4>YouTube Training Links</h4><ul><li><a href="https://www.youtube.com/watch?v=XU95qPuiIKI&amp;list=PLnXn1AViWyL6q4rFvFZtJOYPb3TWUpFEM">Reactive Programming with Project Reactor</a></li><li><a href="https://www.youtube.com/watch?v=EExlnnq5Grs&amp;list=PLqq-6Pq4lTTYPR2oH7kgElMYZhJd4vOGI">Intro to Reactive Programming with RxJava —</a></li></ul><h3>5. Serverless Computing</h3><p>Serverless architecture allows developers to build and deploy applications without worrying about managing the underlying infrastructure. This enhances agility and reduces operational overhead.</p><h4>Related Technologies</h4><ul><li><strong>AWS Lambda:</strong> Lets you run code in response to events without managing servers.</li><li><strong>Azure Functions:</strong> A serverless compute service for running small pieces of code.</li><li><strong>Google Cloud Functions:</strong> A lightweight solution for event-based functions.</li></ul><h4>Recommended Books</h4><ul><li>“Serverless Architectures on AWS” by Peter Sbarski</li><li>“Building Serverless Applications with Python” by Mohamed Labouardy</li></ul><h4>YouTube Training Links</h4><ul><li><a href="https://www.youtube.com/watch?v=N-ejay6w2As&amp;list=PLLv1Hn1N3bRzke3cYLX_yl9CEEr0J0bf7">AWS Lambda Tutorial</a></li><li><a href="https://www.youtube.com/watch?v=eS5GJkI69Qg&amp;list=PLMWaZteqtEaLRsSynAsaS_aLzDPBUU4CV">Serverless Computing with Azure Function</a>s</li></ul><h3>6. Event-Driven Architecture</h3><p>Event-driven systems are designed to react to events as they occur, providing a responsive and scalable approach to building modern applications.</p><h4>Related Technologies</h4><ul><li><strong>Apache Kafka:</strong> A distributed event streaming platform for handling massive event flows.</li><li><strong>RabbitMQ:</strong> A reliable messaging system for communication between services.</li><li><strong>AWS SNS/SQS:</strong> AWS services for managing and processing message queues.</li></ul><h4>Recommended Books</h4><ul><li>“Designing Event-Driven Systems” by Ben Stopford</li><li>“Kafka: The Definitive Guide” by Neha Narkhede, Gwen Shapira, and Todd Palino</li></ul><h4>YouTube Training Links</h4><ul><li><a href="https://www.youtube.com/watch?v=-DyWhcX3Dpc&amp;list=PLa7VYi0yPIH2PelhRHoFR5iQgflg-y6JA">Kafka Essentials</a></li><li><a href="https://www.youtube.com/watch?v=iQ4kENLfaNI&amp;list=PLalrWAGybpB-UHbRDhFsBgXJM1g6T4IvO">RabbitMQ Tutorial for Beginners — TechWorld with Nana</a></li></ul><h3>7. Security Best Practices</h3><p>In today’s environment, security is paramount. Software architects must incorporate robust security measures to protect applications from various threats.</p><h4>Related Technologies</h4><ul><li><strong>Spring Security:</strong> A comprehensive framework for securing Java applications.</li><li><strong>JWT (JSON Web Tokens):</strong> A secure way of transmitting claims between parties.</li><li><strong>OWASP Tools:</strong> Tools from the Open Web Application Security Project to safeguard applications.</li></ul><h4>Recommended Books</h4><ul><li>“Spring Security in Action” by Laurentiu Spilca</li><li>“Java Security: Writing Secure Code” by Scott Oaks</li></ul><h4>YouTube Training Links</h4><ul><li><a href="https://www.youtube.com/watch?v=sm-8qfMWEV8&amp;list=PLqq-6Pq4lTTYTEooakHchTGglSvkZAjnE">Spring Security Basics — Java Brains</a></li><li><a href="https://www.youtube.com/watch?v=YYe0FdfdgDU">OWASP Top 10 Security Vulnerabilities</a></li></ul><h3>8. DevOps and CI/CD</h3><p>Integrating development and operations through DevOps practices and CI/CD pipelines ensures rapid, reliable, and efficient software delivery.</p><h4>Related Technologies</h4><ul><li><strong>Jenkins:</strong> An automation server that facilitates continuous integration and deployment.</li><li><strong>GitLab CI/CD:</strong> A robust platform for managing CI/CD pipelines.</li><li><strong>Travis CI:</strong> A cloud-based service for automating code building and testing.</li></ul><h4>Recommended Books</h4><ul><li>“The DevOps Handbook” by Gene Kim, Patrick Debois, John Willis, and Jez Humble</li><li>“Continuous Delivery: Reliable Software Releases through Build, Test, and Deployment Automation” by Jez Humble and David Farley</li></ul><h4>YouTube Training Links</h4><ul><li><a href="https://www.youtube.com/watch?v=lhFvMsy6VX8&amp;list=PLy7NrYWoggjwwEpZO8sscD9X6EH39njz6">DevOps Tutorials</a></li><li><a href="https://www.youtube.com/watch?v=R8_veQiYBjI&amp;list=PLy7NrYWoggjzSIlwxeBbcgfAdYoxCIrM2">CI/CD with Jenkins — TechWorld with Nan</a>a</li></ul><h3>Conclusion</h3><p>The role of a Java software architect continues to evolve as new technologies and practices emerge. To stay ahead, architects must not only be experts in Java but also be proficient in modern architectural patterns, cloud-native solutions, microservices, containerization, security, and much more. Continuous learning through the recommended books, hands-on practice, and YouTube resources will help you build resilient, scalable, and efficient applications that meet today’s demanding digital landscape.</p><p>By mastering these areas, Java architects will be well-equipped to drive innovation and lead their organizations toward success in an increasingly complex technological environment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecb94bec658b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Microservices to Serverless: The Ultimate Guide to Modern Application Architectures]]></title>
            <link>https://medium.com/@priyankapruthe/from-microservices-to-serverless-the-ultimate-guide-to-modern-application-architectures-fd0b71d3057b?source=rss-95172fd0035f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd0b71d3057b</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[serverless-architecture]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[migration]]></category>
            <dc:creator><![CDATA[priyanka pruthi]]></dc:creator>
            <pubDate>Mon, 06 Jan 2025 10:42:01 GMT</pubDate>
            <atom:updated>2025-01-06T10:42:01.510Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unleashing the Power of Microservices and Serverless</h3><p>The tech world is buzzing with terms like <strong>Microservices</strong> and <strong>Serverless</strong>, but what do they really mean, and how can they supercharge your applications? In this guide, we’ll break down the evolution from microservices to serverless computing, showing you how these innovations can help you build faster, more scalable, and cost-effective applications. Buckle up for a journey through the latest in software architecture!</p><h3>1. Microservices: Breaking Down the Monolith</h3><h4>What Are Microservices?</h4><p>Imagine you’re building a huge, bustling city. Instead of having one massive building that serves every purpose (like a giant skyscraper with shops, offices, and apartments all mixed together), you decide to build separate buildings for each function: a shopping mall, an office tower, and residential apartments. This is essentially what <strong>microservices</strong> do for your software.</p><p><strong>Key Features:</strong></p><ul><li><strong>Modularity</strong>: Like city blocks, each microservice handles a specific task. For example, one service manages user authentication, while another handles payment processing.</li><li><strong>Independence</strong>: Each service operates independently but communicates with others through well-defined APIs, much like city buildings connected by roads.</li><li><strong>Flexibility</strong>: Teams can use different technologies for different services, like having a high-tech office building and a vintage-style shopping mall.</li></ul><p><strong>Example:</strong></p><p>For an e-commerce platform, you might have separate microservices for:</p><ul><li><strong>User Management</strong>: Handles user registration, login, and profile updates.</li><li><strong>Product Catalog</strong>: Manages product listings and inventory.</li><li><strong>Order Processing</strong>: Handles shopping carts, orders, and payments.</li><li><strong>Shipping</strong>: Manages delivery and tracking.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t8N5nyURPTaVnaZPC-8nfg.png" /></figure><p><strong>Pros:</strong></p><ul><li><strong>Scalability</strong>: Scale each service independently based on its demand.</li><li><strong>Flexibility</strong>: Use different technologies and frameworks for each service.</li><li><strong>Resilience</strong>: If one service fails, the others continue to function.</li></ul><p><strong>Cons:</strong></p><ul><li><strong>Complexity</strong>: Managing multiple services and their interactions can be complex.</li><li><strong>Deployment Overhead</strong>: Each service requires its own deployment process.</li><li><strong>Data Consistency</strong>: Ensuring consistent data across services can be challenging.</li></ul><h3>2. Serverless: Letting Go of Server Management</h3><h4>What Is Serverless?</h4><p>Imagine hosting a big party without needing to set up tables and chairs yourself. Instead, you just call a party planner who handles everything for you. <strong>Serverless computing</strong> does the same for your applications: you write the code, and the cloud provider takes care of the servers.</p><p><strong>Key Features:</strong></p><ul><li><strong>Event-Driven</strong>: Your code (functions) runs in response to events like HTTP requests, file uploads, or database changes, similar to reacting to party invitations.</li><li><strong>Automatic Scaling</strong>: Functions scale automatically based on demand. Think of it as having an army of party planners who show up exactly when needed.</li><li><strong>Pay-as-You-Go</strong>: You’re charged based on how long your functions run and the resources they use, like paying only for the hours the party planner works.</li></ul><p><strong>Example:</strong></p><p>For a photo-sharing app, you might use serverless functions for:</p><ul><li><strong>Image Upload</strong>: Automatically resize and optimize images when uploaded.</li><li><strong>User Notifications</strong>: Send notifications when someone likes or comments on a photo.</li><li><strong>Data Processing</strong>: Analyze and categorize images.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ylayS7fZe4pEzz1w.png" /></figure><p><strong>Pros:</strong></p><ul><li><strong>No Server Management</strong>: Focus solely on writing and deploying code.</li><li><strong>Scalability</strong>: Functions scale automatically based on incoming events.</li><li><strong>Cost Efficiency</strong>: Pay only for the compute time and resources your code actually uses.</li></ul><p><strong>Cons:</strong></p><ul><li><strong>Cold Starts</strong>: Initial function invocations might be slower (like waiting for the party planner to arrive).</li><li><strong>Execution Limits</strong>: Functions may have time and resource limits.</li><li><strong>Vendor Lock-In</strong>: Tied to a specific cloud provider’s services and features.</li></ul><h3>3. Microservices vs. Serverless: The Showdown</h3><p><strong>Complexity:</strong></p><ul><li><strong>Microservices</strong>: Like managing a city with various buildings, it requires handling multiple services and their interactions.</li><li><strong>Serverless</strong>: Simplifies operations by focusing on individual functions and event triggers.</li></ul><p><strong>Scaling:</strong></p><ul><li><strong>Microservices</strong>: Scale each service independently based on its needs.</li><li><strong>Serverless</strong>: Functions scale automatically with demand.</li></ul><p><strong>Cost Management:</strong></p><ul><li><strong>Microservices</strong>: Costs are related to infrastructure and resources regardless of usage.</li><li><strong>Serverless</strong>: Costs are based on actual usage, with a pay-as-you-go model.</li></ul><p><strong>Development and Deployment:</strong></p><ul><li><strong>Microservices</strong>: Requires setting up CI/CD pipelines and managing deployments for each service.</li><li><strong>Serverless</strong>: Simplifies deployment with event-driven functions and less infrastructure management.</li></ul><p><strong>Visual Comparison:</strong></p><p><em>Microservices: Building a city with distinct, interconnected buildings. Serverless: Hiring temporary workers for specific tasks.</em></p><h3>4. When to Choose What?</h3><p><strong>Choose Microservices When:</strong></p><ul><li><strong>You Have Complex Applications</strong>: With multiple components needing separate management.</li><li><strong>Different Technologies Are Needed</strong>: For various parts of the application.</li><li><strong>Data Independence Is Key</strong>: Each component benefits from its own data store.</li></ul><p><strong>Choose Serverless When:</strong></p><ul><li><strong>You Have Event-Driven Workloads</strong>: Like responding to user actions or data changes.</li><li><strong>Cost Efficiency Is Crucial</strong>: Pay only for actual compute time.</li><li><strong>You Want to Minimize Operations</strong>: Focus on writing code without managing servers.</li></ul><h3>5. Conclusion</h3><p>Whether you’re managing a complex city of microservices or leveraging the simplicity of serverless functions, understanding these architectures can help you build more efficient and scalable applications. Microservices offer flexibility and modularity, perfect for intricate systems, while serverless computing provides effortless scalability and cost savings for event-driven applications. By choosing the right approach for your needs, you can unlock new levels of performance and efficiency in your software development journey.</p><p><strong>Ready to Transform Your Applications?</strong> Dive into the world of microservices or serverless computing and take your software architecture to the next level!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd0b71d3057b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering SOLID Principles: Crafting Flexible and Maintainable Java Applications]]></title>
            <link>https://medium.com/@priyankapruthe/mastering-solid-principles-crafting-flexible-and-maintainable-java-applications-a3a4bda616ed?source=rss-95172fd0035f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3a4bda616ed</guid>
            <category><![CDATA[solid-principles-in-java]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[solid-principles]]></category>
            <dc:creator><![CDATA[priyanka pruthi]]></dc:creator>
            <pubDate>Sun, 11 Feb 2024 19:19:56 GMT</pubDate>
            <atom:updated>2024-02-11T19:19:56.076Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lJ2ixDxnNFMJXLTgQ-XT0A.png" /></figure><h4>Introduction</h4><p>As a software developer, you might have encountered the term “<strong>SOLID Principles</strong>” but not fully grasped its essence or struggled to explain it during job interviews. Admitting that theory isn’t my forte, I still recognize the value of understanding SOLID principles at least theoretically. Hence, I’ve crafted this straightforward guide to demystify these principles for those who, like me, aim to improve their coding practices.</p><p><strong>This exploration promises to enlighten you on several fronts:</strong></p><ul><li>The criticality of developing robust, maintainable software.</li><li>A clear understanding of what SOLID principles entail.</li><li>Practical advice on the dos and don’ts when applying these principles.</li></ul><h4>The Imperative of Crafting Robust, Maintainable Code</h4><p><strong>Embracing Change</strong></p><p>Coding is an art form, especially when it comes to maintenance. All developers face the need to revise their code to meet evolving requirements. Given that change is the only constant, writing adaptable code is not just a necessity but a skill.</p><p><strong>Speed and Agility</strong></p><p>In the competitive tech landscape, speed is of the essence. Agile development, characterized by rapid iterations and continuous improvement, requires a foundation of solid coding principles. The SOLID principles equip developers to make swift, seamless changes, enhancing both agility and product quality.</p><h4>Demystifying SOLID Principles</h4><p><strong>SOLID</strong> principles are foundational guidelines in software design that promote code that is robust, understandable, maintainable, and flexible. These principles were brought to the forefront by <strong>Robert C. Martin (Uncle Bob) around 2004 </strong>and encompass the following:</p><ul><li><strong>S: Single Responsibility Principle (SRP)</strong></li><li><strong>O: Open-Closed Principle (OCP)</strong></li><li><strong>L: Liskov Substitution Principle (LSP)</strong></li><li><strong>I: Interface Segregation Principle (ISP)</strong></li><li><strong>D: Dependency Inversion Principle (DIP)</strong></li></ul><p>Following these principles facilitates writing code that is <strong>testable, comprehensible, extendable, and flexible</strong>, thereby enhancing <strong>functionality adjustments</strong>, swapping implementations effortlessly, and navigating the codebase with ease.</p><blockquote>To tackle this scenario effectively, let’s apply the SOLID principles to design a Java application that calculates salaries for employees in different departments like HR and Engineering. This approach will ensure our design is robust, maintainable, and flexible.</blockquote><h3>Single Responsibility Principle (SRP)</h3><p>It indicates that a class, function, or module should have one, and only one, reason to change, ensuring a singular focus and thus promoting cohesion.</p><p>For example, if there’s a need in our application for logging, caching, or storing then these <strong>concerns need to be separated and designed into separate classes</strong> each fulfilling its own SRP.</p><p>Each class should have a single responsibility. We’ll separate the concerns by having classes dedicated to representing employees and another set of classes focused on calculating salaries.</p><h3>Open-Closed Principle (OCP)</h3><p>Encourages designing software entities in a way that they are open for extension but closed for modification, fostering scalability and reducing the risk of bugs when adding new features.</p><p>We’ll use interfaces and abstract classes to define behaviors that can be extended for different departments without needing to modify existing code.</p><p><strong>Note: Bug fixes are permitted, and if required, they may involve changing the current code. If not, our plan for repairing them</strong></p><h3>Liskov Substitution Principle (LSP)</h3><p>Subclasses will be substitutable for their base classes or interfaces. This ensures that the use of a subclass in place of a base class won’t break the application.</p><p>So basically, we’re talking about using interfaces and abstract classes.</p><h3>Interface Segregation Principle (ISP)</h3><p>Advises against forcing a class to implement interfaces it doesn’t use, promoting fine-grained interfaces that enhance system modularity.</p><h3>Dependency Inversion Principle (DIP)</h3><p>High-level modules will not depend on low-level modules but on abstractions. This principle aims to reduce dependencies among code components, increasing modularity and flexibility.</p><p>This decouples the specifics of salary calculations from the representation of employees.</p><p><strong>Let’s dive into the code:</strong></p><pre>// Define an interface for salary calculation to adhere to ISP and DIP<br>interface SalaryCalculator {<br>    double calculateSalary();<br>}<br><br>// Abstract class for Employee to follow OCP and LSP<br>abstract class Employee {<br>    protected String id;<br>    protected String name;<br>    protected SalaryCalculator salaryCalculator;<br>    public Employee(String id, String name, SalaryCalculator salaryCalculator) {<br>        this.id = id;<br>        this.name = name;<br>        this.salaryCalculator = salaryCalculator;<br>    }<br>    public double getSalary() {<br>        return salaryCalculator.calculateSalary();<br>    }// Additional common methods for employees can be added here<br>}<br><br>// Concrete SalaryCalculator implementations for each department<br>class HRSalaryCalculator implements SalaryCalculator {<br>    private double baseSalary;<br>    public HRSalaryCalculator(double baseSalary) {<br>        this.baseSalary = baseSalary;<br>    }<br>    @Override<br>    public double calculateSalary() {<br>        // HR salary calculation logic<br>        return baseSalary + (baseSalary * 0.1); // Example calculation<br>    }<br>} <br><br>class DeveloperSalaryCalculator implements SalaryCalculator {<br>    private double baseSalary;<br>    public  DeveloperSalaryCalculator(double baseSalary) {<br>        this.baseSalary = baseSalary;<br>    }<br>    @Override<br>    public double calculateSalary() {<br>        // Developer salary calculation logic<br>        return baseSalary + (baseSalary * 0.15); // Example calculation<br>    }<br>}<br> <br><br>// Concrete Employee subclasses for HR and Engineering departments<br>class HREmployee extends Employee {<br>    public HREmployee(String id, String name, SalaryCalculator salaryCalculator) {<br>        super(id, name, salaryCalculator);<br>    }<br>}<br><br>class EngineeringEmployee extends Employee {<br>    public AccountingEmployee(String id, String name, SalaryCalculator salaryCalculator) {<br>        super(id, name, salaryCalculator);<br>    }<br>}<br><br><br>// Usage<br>public class Main {<br>    public static void main(String[] args) {<br>        SalaryCalculator hrSalaryCalculator = new HRSalaryCalculator(3000);<br>        Employee hrEmployee = new HREmployee(&quot;1&quot;, &quot;John Doe&quot;, hrSalaryCalculator);<br>        SalaryCalculator engineeringSalaryCalculator = new EngineeringSalaryCalculator(3000);<br>        Employee engineeringEmployee = new EngineeringEmployee(&quot;2&quot;, &quot;Jane Doe&quot;, engineeringSalaryCalculator);<br>        System.out.println(&quot;HR Employee Salary: &quot; + hrEmployee.getSalary());<br>        System.out.println(&quot;Engineering Employee Salary: &quot; + engineeringEmployee.getSalary());<br>    }<br>}</pre><p><strong>In this design:</strong></p><ul><li><strong>SRP</strong> is maintained by having separate classes for employee representation and salary calculation.</li><li><strong>OCP</strong> is achieved through the use of the SalaryCalculator interface, allowing new salary calculation strategies to be added without modifying existing code.</li><li><strong>LSP</strong> is ensured as subclasses of Employee can replace their parent class without affecting the functionality.</li><li><strong>ISP</strong> is adhered to by creating a focused SalaryCalculator interface that Employee classes depend on for salary calculation.</li><li><strong>DIP</strong> is observed by depending on the SalaryCalculator abstraction for salary calculations rather than concrete implementations.</li></ul><h4>Conclusion</h4><p>Embarking on the journey of SOLID principles is akin to refining our craftsmanship in software development. While these principles serve as a beacon, guiding us towards excellence, it’s crucial to apply them judiciously, balancing theory with practicality. The ultimate aim is to forge code that stands the test of time — easy to modify, understand, maintain, and test. As we weave these principles into our daily coding practices, the lines between them blur, leading us toward the creation of software that’s not just functional but truly resilient and maintainable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3a4bda616ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Kafka: Unveiling High Throughput, Availability, Scalability, and Replayability with…]]></title>
            <link>https://medium.com/@priyankapruthe/mastering-kafka-unveiling-high-throughput-availability-scalability-and-replayability-with-785d64125f78?source=rss-95172fd0035f------2</link>
            <guid isPermaLink="false">https://medium.com/p/785d64125f78</guid>
            <category><![CDATA[kafka-consumer]]></category>
            <category><![CDATA[availability]]></category>
            <category><![CDATA[replayability]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[scalability]]></category>
            <dc:creator><![CDATA[priyanka pruthi]]></dc:creator>
            <pubDate>Thu, 01 Feb 2024 06:30:56 GMT</pubDate>
            <atom:updated>2024-02-01T06:33:29.717Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Kafka: Unveiling High Throughput, Availability, Scalability, and Replayability with Practical Code Insights”</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fx6tuLGHEis6KNIA0-x16w.png" /><figcaption>Unveiling High Throughput, Availability, Scalability, and Replayability</figcaption></figure><p>Apache Kafka has established itself as a fundamental platform in the landscape of data streaming and processing, renowned for its high throughput, robust availability, impressive scalability, and unique replayability features. This article aims to explore the core components of Kafka, offering insights into its architecture and operational dynamics, supplemented with practical code examples.</p><h4><strong>High Throughput</strong></h4><p>Efficient Data Processing Kafka’s exceptional throughput capabilities stem from its design, which enables the handling of millions of messages per second. This is achieved through efficient topic partitioning and the utilization of sequential disk I/O.</p><p>Code Example: To send messages to a specified Kafka topic using KafkaTemplate.</p><pre>import org.springframework.kafka.core.KafkaTemplate;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.stereotype.Service;<br><br>@Service<br>public class KafkaProducerService {<br><br>    @Autowired<br>    private KafkaTemplate&lt;String, String&gt; kafkaTemplate;<br><br>    public void sendMessage(String message, String topicName) {<br>        kafkaTemplate.send(topicName, message);<br>    }<br>}<br><br></pre><h4><strong>Availability</strong></h4><p>Ensuring Continuous Data Access Kafka guarantees high availability through its distributed architecture. It replicates data across multiple nodes, safeguarding against data loss during a node failure.</p><p>Code Example: Configuring Replication in Kafka Topic</p><pre>kafka-topics --create --bootstrap-server localhost:9092 \<br>             --replication-factor 3 --partitions 1 --topic my-replicated-topic</pre><p>This command-line example shows how to create a Kafka topic with a replication factor of three, ensuring that each message is stored across three different nodes.</p><p>In Spring Boot, topic configurations are often set in the application.properties or application.yml file.</p><pre>spring:<br>  kafka:<br>    producer:<br>      bootstrap-servers: localhost:9092<br>    topic:<br>      name: myTopic<br>      partitions: 3<br>      replication-factor: 2</pre><h4><strong>Scalability</strong></h4><p>Meeting Growing Data Demands Kafka’s distributed nature facilitates easy scalability to accommodate growing data demands. It allows the addition of more brokers to the cluster without downtime.</p><p>Code Example: Configure your Kafka consumers in application.properties or application.yml to control aspects like concurrency (number of threads for consuming messages).</p><pre>spring:<br>  kafka:<br>    consumer:<br>      bootstrap-servers: localhost:9092<br>      group-id: myGroup<br>      auto-offset-reset: earliest<br>    listener:<br>      concurrency: 3</pre><h4>Replayability</h4><p>Rewinding Data Streams One of Kafka’s unique features is its ability to replay messages from a specified point in time, which is crucial for various use cases including debugging and system recovery.</p><p>Code Example: Consuming Messages from a Specific Offset using Consumer.seek().</p><h4>1. Create a Kafka Listener Container Factory</h4><p>First, define a ConcurrentKafkaListenerContainerFactory in your configuration. This factory is responsible for creating the listener containers for the @KafkaListener annotations.</p><pre>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;<br>import org.springframework.kafka.core.ConsumerFactory;<br><br>@Configuration<br>public class KafkaConfig {<br><br>    @Bean<br>    public ConcurrentKafkaListenerContainerFactory&lt;String, String&gt; kafkaListenerContainerFactory(ConsumerFactory&lt;String, String&gt; consumerFactory) {<br>        ConcurrentKafkaListenerContainerFactory&lt;String, String&gt; factory = new ConcurrentKafkaListenerContainerFactory&lt;&gt;();<br>        factory.setConsumerFactory(consumerFactory);<br>        return factory;<br>    }<br>}<br></pre><h4>2. Implement the Kafka Consumer with Manual Offset Control</h4><p>In your service, implement the logic to manually seek to a specific offset if required. You can inject the ConsumerFactory to create an KafkaConsumer instance for this purpose.</p><pre>import org.apache.kafka.clients.consumer.Consumer;<br>import org.apache.kafka.clients.consumer.KafkaConsumer;<br>import org.apache.kafka.common.TopicPartition;<br>import org.springframework.kafka.core.ConsumerFactory;<br>import org.springframework.stereotype.Service;<br><br>import java.util.Collections;<br><br>@Service<br>public class KafkaReplayService {<br><br>    private final ConsumerFactory&lt;String, String&gt; consumerFactory;<br><br>    public KafkaReplayService(ConsumerFactory&lt;String, String&gt; consumerFactory) {<br>        this.consumerFactory = consumerFactory;<br>    }<br><br>    public void replayFromOffset(String topic, int partition, long offset) {<br>        Consumer&lt;String, String&gt; consumer = consumerFactory.createConsumer();<br>        consumer.assign(Collections.singletonList(new TopicPartition(topic, partition)));<br>        consumer.seek(new TopicPartition(topic, partition), offset);<br><br>        // Consume messages and process them<br>        // ...<br><br>        consumer.close();<br>    }<br>}J</pre><h4>3. Usage</h4><p>You can call the replayFromOffset method with the specific topic, partition, and offset from which you want to start reprocessing messages. For example:</p><pre>@Autowired<br>private KafkaReplayService kafkaReplayService;<br><br>// ...<br><br>kafkaReplayService.replayFromOffset(&quot;yourTopic&quot;, 0, 12345L); // Replay from offset 12345 in partition 0 of &#39;yourTopic&#39;</pre><h4>Note</h4><ul><li>The replayFromOffset method should be used with caution, as it creates a new consumer instance every time it is called. Make sure to close the consumer after use to avoid resource leaks.</li><li>Managing offsets manually requires a good understanding of Kafka’s offset management. Ensure that this approach fits your application’s requirements and that you handle edge cases (like offsets that are out of range) appropriately.</li><li>This example is intended for scenarios where you need fine-grained control over offset management. For many use cases, Kafka’s built-in offset management and replay capabilities (like setting auto.offset.reset to earliest) may be sufficient.</li></ul><h4><strong>Conclusion</strong></h4><p>Kafka’s Role in Data-Driven Solutions Kafka’s architectural prowess in handling high-volume data streams, coupled with its fault tolerance, scalability, and data replayability, makes it an indispensable tool in modern data architectures. From financial transactions to real-time analytics in IoT applications, Kafka’s role is pivotal. The provided code snippets offer a glimpse into Kafka’s operational aspects, showcasing its practical application in various scenarios. As data continues to drive decision-making processes, Kafka’s relevance and utility are set to grow even further.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=785d64125f78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking Simplicity: A Deep Dive into Java 17’s Sealed Classes, Interfaces and Records]]></title>
            <link>https://medium.com/@priyankapruthe/unlocking-simplicity-a-deep-dive-into-java-17s-sealed-classes-interfaces-and-records-89bcf28a636f?source=rss-95172fd0035f------2</link>
            <guid isPermaLink="false">https://medium.com/p/89bcf28a636f</guid>
            <dc:creator><![CDATA[priyanka pruthi]]></dc:creator>
            <pubDate>Thu, 04 Jan 2024 12:50:16 GMT</pubDate>
            <atom:updated>2024-01-04T12:50:16.582Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*7BN0v1DGEyNrZu1nwuK4Pg.gif" /></figure><p>Java 17 is here, and it brings with it a duo of features that promises to transform your code into a masterpiece of simplicity and clarity. Let’s embark on a journey into the world of sealed classes and records, where elegance meets efficiency, and code becomes a work of art.</p><h4>Sealed Classes: The Guardians of Hierarchy</h4><p>Imagine a class hierarchy where not just anyone can waltz in and extend your classes. Enter sealed classes, the gatekeepers of your class hierarchy. With the power to permit only chosen subclasses, they add an extra layer of control, turning your code into a well-guarded fortress.<br>Sealed interfaces follow the same principle as sealed classes, controlling which classes can implement them. This allows interface designers to define a closed set of implementing classes, promoting a more stable and secure API.</p><pre>public sealed interface CreateLoginResult permits Error, Token {<br><br>}</pre><p>Sealed classes and interfaces set the stage for a refined, well-orchestrated inheritance, offering both clarity and security.</p><h4>Record: The Virtuosos of Data Representation</h4><p>In essence, records are a concise way to model immutable data in Java. They were introduced in Java 14 as a preview feature and became stable with overwhelming approval in Java 16. With Java 17, records continue to shine, providing a clean and expressive syntax for creating simple, data-carrying classes.</p><p>Declaring a record is remarkably concise. You only need to specify the fields, and the compiler automatically generates methods like equals(), hashCode(), and toString().</p><p>Records are widely used in modern Java applications, especially in scenarios where simple data classes are prevalent, such as in microservices, data processing, or API development.</p><pre>import java.util.Date;<br>import lombok.Builder;<br><br>@Builder<br>public record Error(String message,<br>                       String code,<br>                       Date timestamp,<br>                       boolean retryable) implements CreateLoginResult {<br><br>}</pre><p>While records are powerful for simple data-carrying classes, they might not be suitable for complex scenarios where custom logic or behavior is required. In such cases, a traditional class with explicit methods might be more appropriate.</p><h3>How we used Sealed Interfaces and Records to simplify code implementation</h3><p>Consider the following scenario: you have to design a login process for your application using either UserName/email and Password or Phone/email address and OTP with 2FA authentications.</p><p><strong>LoginRequest: </strong>This is used to represent request received for login</p><p>Initial Code</p><pre>import lombok.Builder;<br>import lombok.Data;<br>import lombok.NoArgsConstructor;<br>import lombok.AllArgsConstructor;<br>import com.fasterxml.jackson.annotation.JsonProperty;<br><br>@Data<br>@Builder<br>@NoArgsConstructor<br>@AllArgsConstructor<br>public class LoginRequest {<br>    private LoginType loginType;<br>    private String phoneNumber;<br>    private String userName;<br>    private String password;<br>    @JsonProperty(&quot;PIN&quot;)<br>    private String pin;<br>    private String otp;<br>    private String refreshToken;<br>}<br></pre><p>Java 17 code</p><pre>import lombok.Builder;<br>import lombok.Data;<br>import lombok.NoArgsConstructor;<br>import lombok.AllArgsConstructor;<br>import com.fasterxml.jackson.annotation.JsonProperty;<br><br>public record LoginRequest {<br>    private LoginType loginType;<br>    private String phoneNumber;<br>    private String userName;<br>    private String password;<br>    @JsonProperty(&quot;PIN&quot;)<br>    private String pin;<br>    private String otp;<br>    private String refreshToken;<br>}</pre><p><strong>To return response for Login API below classes are defined initially</strong></p><p><strong>LoginResponse:</strong> This class is used to return result for successful Login.</p><pre>import lombok.Builder;<br>import lombok.Data;<br>import com.fasterxml.jackson.annotation.JsonProperty;<br><br>@Data<br>@Builder<br>public class LoginResponse {<br>    private String accessToken;<br>    private String refreshToken;<br>    private Integer accessExpiresIn;<br>    private Integer refreshExpiresIn;<br>    private String rememberMeCookie;<br>}</pre><p><strong>TwoFactorAuthenticationResponse:</strong> This class is used to return result for successful processing for 2FA request input.</p><pre>import lombok.Builder;<br>import lombok.Data;<br>import java.util.List;<br><br>@Data<br>@Builder<br>public class TwoFactorAuthenticationResponse {<br>    private String id;<br>    private String code;<br>    private String timeStamp;<br>    private boolean retryable;<br>    private String severity;<br>    private List&lt;DetailsDTO&gt; details;<br>}</pre><p><strong>LoginType</strong>: This enum is representing all available types allowed for Login</p><pre><br>import com.fasterxml.jackson.annotation.JsonValue;<br><br>@RequiredArgsConstructor<br>public enum LoginType {<br>    PHONE_NUMBER(&quot;phoneNumber&quot;),<br>    EMAIL(&quot;email&quot;),<br>    USERNAME(&quot;username&quot;)<br><br>    private final String value;<br><br>    @JsonValue<br>    public String getValue() {<br>        return value;<br>    }<br>}</pre><p>OtpLoginResponse</p><pre>import lombok.Builder;<br>import lombok.Getter;<br>import lombok.Setter;<br><br>import java.util.List;<br><br>@Builder<br>@Getter<br>@Setter<br>public class OtpLoginResponse{<br>    private String context = null;<br>    private String serviceId = null;<br>    private ServiceTypeEnum serviceType = null;<br>    private String otp = null;<br>}</pre><p><strong>Java 17 code<br></strong>We have used Sealed interface and Record feature to redefine response objects</p><pre>public sealed interface OtpSessionResult permits <br>TwoFactorAuthentication, Token {<br><br>}</pre><pre>public sealed interface SessionResult permits Error, Token {<br><br>}</pre><pre>import java.util.Date;<br>import lombok.Builder;<br><br>@Builder<br>public record Error(String id,<br>                       String code,<br>                       Date timestamp,<br>                       boolean retryable) implements SessionResult {<br><br>}</pre><pre>import lombok.Builder;<br><br>@Builder<br>public record Token(String accessToken,<br>                    String refreshToken,<br>                    Integer accessExpiresIn,<br>                    Integer refreshExpiresIn,<br>                    String rememberMeCookie) implements SessionResult, <br>OtpSessionResult {<br><br>}</pre><pre>import java.util.List;<br>import lombok.Builder;<br><br>@Builder<br>public record TwoFactorAuthentication(String id,<br>                      String code,<br>                      String timestamp,<br>                      boolean retryable,<br>                      String severity,<br>                      List&lt;Detail&gt; details) implements SessionResult {<br><br>  @Builder<br>  public record Detail(Token token, List&lt;ServiceCharacteristic&gt; availableTypes) {<br><br>  }<br>}<br></pre><pre>import lombok.Builder;<br>import com.fasterxml.jackson.annotation.JsonProperty;<br><br>@Builder<br>public record LoginRequest {<br>    private LoginType loginType;<br>    private String serviceId;<br>    private String userName;<br>    private String password;<br>    @JsonProperty(&quot;PIN&quot;)<br>    private String pin;<br>    private String otp;<br>    private String refreshToken;<br>}</pre><p><strong>We used Strategy design pattern to provide logic for various Login types in initial code which is removed in Java 17 code implementation.</strong></p><p><strong>Below code is representing initial code</strong></p><pre>import org.springframework.http.ResponseEntity;<br><br>public interface LoginStrategy {<br>    ResponseEntity&lt;Object&gt; getResponse(LoginRequest loginRequest) throws Exception;<br>}</pre><pre>import org.springframework.http.ResponseEntity;<br>import lombok.RequiredArgsConstructor;<br>import java.util.Collections;<br>import java.util.Date;<br>import java.util.Optional;<br><br>@RequiredArgsConstructor<br>public class TelecomLoginStrategy implements LoginStrategy {<br>    final private UserLoginRepository userLoginRepository;<br>    final private LoginUtilityService loginUtilityService;<br><br>    @Override<br>    public ResponseEntity&lt;Object&gt; getResponse(LoginRequest loginRequest){<br>        Optional&lt;UserLogin&gt; userLoginResponse = userLoginRepository.findByServiceId(loginRequest.getServiceId());<br>        String otp = userLoginResponse.get().getOtp();<br>        if (!otp.equalsIgnoreCase(loginRequest.getPin())) {<br>            throw new BadRequestException(&quot;Incorrect OTP&quot;);<br>        }<br>        boolean levelUpEnabled = !userLoginResponse.get().isRememberLevelup();<br><br>        if (levelUpEnabled) {<br>            TwoFactorAuthenticationResponse levelupResponse = TwoFactorAuthenticationResponse.builder()<br>                    .id(Utility.generateUUID())<br>                    .code(&quot;app.security.authentication.wrong.pin&quot;)<br>                    .severity(&quot;WARN&quot;)<br>                    .timeStamp(new Date().toString())<br>                    .retryable(false)<br>                    .details(Collections.singletonList(DetailsDTO.builder().token(loginUtilityService.getLoginResponse(userLoginResponse.get()))<br>                            .availableTypes(userLoginResponse.get().getLevelUp())<br>                            .build())).build();<br><br>            return ResponseEntity.unprocessableEntity().body(levelupResponse);<br>        }<br>        return ResponseEntity.ok(loginUtilityService.getLoginResponse(userLoginResponse.get()));<br>    }<br>}</pre><pre>import org.springframework.http.ResponseEntity;<br><br>import java.util.Optional;<br><br>public class EmailLoginStrategy implements LoginStrategy {<br>   final private UserLoginRepository userLoginRepository;<br>   final private LoginUtilityService loginUtilityService;<br><br>    @Override<br>    public ResponseEntity&lt;Object&gt; getResponse(LoginRequest loginRequest) throws Exception {<br>        Optional&lt;UserLogin&gt; userLoginResponse = userLoginRepository.findByServiceId(loginRequest.getServiceId());<br>        String otp = userLoginResponse.get().getOtp();<br><br>        if (otp.equalsIgnoreCase(loginRequest.getPin())) {<br>            return ResponseEntity.ok(loginUtilityService.getLoginResponse(userLoginResponse.get()));<br>        } else {<br>            throw new BadRequestException(&quot;Incorrect OTP&quot;);<br>        }<br>    }<br>}</pre><p><strong>Service Interface and Logic Implementation</strong></p><p>Login Service Interface</p><pre>import org.springframework.http.ResponseEntity;<br><br>public interface LoginService {<br>    public ResponseEntity&lt;Object&gt; createSession(LoginRequest loginRequest);<br><br>    public ResponseEntity&lt;Object&gt; createOtpSession(LoginRequest loginRequest);<br><br>    public ResponseEntity&lt;Object&gt; createEmailSession(String token, LoginRequest loginRequest);<br>}</pre><p>Initial LoginService logic implementation</p><pre>import io.jsonwebtoken.Jwts;<br>import io.jsonwebtoken.SignatureAlgorithm;<br>import io.jsonwebtoken.security.Keys;<br>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.http.HttpStatus;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.stereotype.Service;<br><br>import javax.crypto.SecretKey;<br>import java.security.spec.InvalidKeySpecException;<br>import java.time.Instant;<br>import java.util.*;<br><br>@Service<br>@Slf4j<br>@RequiredArgsConstructor<br>public class LoginServiceImpl implements LoginService {<br>    private static final String TRANSFORMATION = &quot;&lt;Set allowed Transformation here&gt;&quot;;<br>   <br>    private final UsersLoginRepository usersLoginRepository;<br>   <br>    private final PasswordDecoder passwordDecoder;<br>   <br>    <br>   <br>    private JwtUtility jwtUtility;<br>  <br>    private LoginUtilityService loginUtilityService;<br><br>    @Override<br>    public ResponseEntity&lt;Object&gt; createSession(LoginRequest loginRequest) {<br>        log.info(&quot;createSession {}: &quot;, loginRequest);<br>        try {<br>            final String password = passwordDecoder.decode(loginRequest.getPassword());<br>            Optional&lt;UserLogin&gt; optionalUser = usersLoginRepository.findByUserNameAndPassword(loginRequest.getUsername(), password);<br>            UserLogin userLogin = optionalUser.get();<br>            return ResponseEntity.ok(getLoginResponse(userLogin));<br>        } catch (NoSuchElementException ex) {<br>            log.error(&quot;createSession NoSuchElementException {}: &quot;, ex.getMessage());<br>            return ResponseEntity.unprocessableEntity().body(&quot;Either your username and password is wrong&quot;);<br><br>        } catch (Exception ex) {<br>            log.error(&quot;createSession Exception {}: &quot;, ex.getMessage());<br>            return new ResponseEntity&lt;&gt;(HttpStatus.INTERNAL_SERVER_ERROR);<br>        }<br>    }<br><br><br>    @Override<br>    public ResponseEntity&lt;Object&gt; createOtpSession(LoginRequest loginRequest) throws Exception {<br>        ServiceTypeStrategy serviceType = new ServiceTypeFactory(jwtUtility, usersLoginRepository,loginUtilityService)<br>                                          .getStrategy(loginRequest.getLoginType());<br>        return serviceType.getResponse(loginRequest);<br>    }<br><br>   <br>    @Override<br>    public ResponseEntity&lt;Object&gt; createEmailSession(String token, LoginRequest loginRequest) {<br>        String userId = jwtUtility.getUserId(token);<br>        Optional&lt;UserLogin&gt; userLogin = null;<br><br>        if (Objects.nonNull(userId))<br>            userLogin = usersLoginRepository.findByUserId(userId);<br><br>        if (Objects.isNull(userLogin))<br>            userLogin = usersLoginRepository.findByEmailId(loginRequest.getServiceId());<br><br>        if (Objects.nonNull(loginRequest.getPin())) {<br>            if (!loginRequest.getPin().equals(userLogin.get().getOtp())) {<br>                log.error(&quot;Incorrect OTP&quot;);<br>                return new ResponseEntity&lt;&gt;(HttpStatus.INTERNAL_SERVER_ERROR);<br>            }<br>        }<br>        if (Objects.nonNull(loginRequest.getOtp())) {<br>            if (!loginRequest.getOtp().equals(userLogin.get().getOtp())) {<br>                log.error(&quot;Incorrect OTP&quot;);<br>                return new ResponseEntity&lt;&gt;(HttpStatus.INTERNAL_SERVER_ERROR);<br>            }<br>        }<br>        if (userLogin.isPresent()) {<br>            return ResponseEntity.ok(OtpLoginResponse.builder()<br>                    .serviceType(loginRequest.getLoginType())<br>                    .context(&quot;emailContact&quot;)<br>                    .otp(userLogin.get().getOtp())<br>                    .serviceId(loginRequest.getServiceId())<br>        } else {<br><br>                    .serviceType(loginRequest.getLoginType())<br>                    .context(&quot;emailContact&quot;)<br>                    .serviceId(loginRequest.getServiceId())<br>        }<br>    }<br><br>    public LoginResponse getLoginResponse(UserLogin response) {<br>        log.info(&quot;getLoginResponse {}: &quot;, response);<br>        try {<br>            return LoginResponse.builder().accessToken(getToken(response, Instant.now(), 5l))<br>                    .accessExpiresIn(18000)<br>                    .refreshToken(getToken(response, Instant.now(), 10l))<br>                    .refreshExpiresIn(36000).build();<br>        } catch (Exception ex) {<br>            log.error(&quot;getLoginResponse Exception {}: &quot;, ex.getMessage());<br>        }<br>        return null;<br>    }<br><br>    public SecretKey createPrivateKey() {<br>        return Keys.secretKeyFor(SignatureAlgorithm.HS256);<br>    }<br><br>    private String getToken(UserLogin response, Instant now, Long duration) <br>      throws InvalidKeySpecException <br>    {<br>        Map&lt;String, Object&gt; claims = new HashMap&lt;&gt;();<br><br>        claims.put(&quot;firstName&quot;, response.getUserName());<br>        claims.put(&quot;lastName&quot;, response.getUserName());<br>        claims.put(&quot;access_restricted&quot;, false);<br>        claims.put(&quot;sub&quot;, response.getUserId());<br><br>        return Jwts.builder()<br>                .addClaims(claims)<br>                .signWith(createPrivateKey(), SignatureAlgorithm.HS256)<br>                .compact();<br>    }</pre><p>Java 17 Code</p><pre><br>import io.jsonwebtoken.Jwts;<br>import io.jsonwebtoken.SignatureAlgorithm;<br>import io.jsonwebtoken.security.Keys;<br>import java.util.Date;<br>import java.util.List;<br>import java.util.Map;<br>import java.util.Optional;<br>import lombok.RequiredArgsConstructor;<br>import org.springframework.stereotype.Service;<br><br>@Service<br>@RequiredArgsConstructor<br>public class LoginService {<br><br>  private final PasswordDecodeService passwordDecodeService;<br>  private final UsersLoginRepository usersLoginRepository;<br>  private final JwtUtility jwtUtility;<br><br>  public CreateSessionResult createSession(final LoginRequest loginRequest) {<br>    final var password = passwordDecodeService.decode(loginRequest.password());<br>    final var user = usersLoginRepository.findByUserNameAndPassword(loginRequest.username(), password);<br>    return user.isPresent()<br>        ? createToken(user.get())<br>        : createError();<br>  }<br><br> public CreateOtpSessionResult createOtpSession(final LoginRequest loginRequest) {<br>    return switch (loginRequest.loginType()) {<br>      case PHONE_NUMBER -&gt; createOtpSessionByPhoneNumber(loginRequest);<br>      case EMAIL -&gt; createOtpSessionByEmail(loginRequest);<br>      default -&gt; throw new CriticalException(&quot;Service type not implemented&quot;);<br>    };<br>  }<br><br>  private Token createToken(final UserLogin user) {<br>    return Token.builder()<br>        .accessToken(createJwtToken(user))<br>        .refreshToken(createJwtToken(user))<br>        .refreshExpiresIn(36000)<br>        .build();<br>  }<br><br>  private String createJwtToken(final UserLogin user) {<br>    final var privateKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);<br>    final Map&lt;String, Object&gt; claims = Map.of(<br>        &quot;firstName&quot;, user.getUserName(),<br>        &quot;lastName&quot;, user.getUserName(),<br>        &quot;access_restricted&quot;, false,<br>        &quot;sub&quot;, user.getUserId()<br>    );<br>    return Jwts.builder()<br>        .addClaims(claims)<br>        .signWith(privateKey, SignatureAlgorithm.HS256)<br>        .compact();<br>  }<br><br>  private Error createError() {<br>    return Error.builder()<br>        .id(Utility.generateUUID())<br>        .code(&quot;app.security.authentication.credentials&quot;)<br>        .timestamp(new Date())<br>        .retryable(false)<br>        .build();<br>  }<br><br>  private OtpSessionResult createOtpSessionByPhoneNumber(final LoginRequest loginRequest) {<br>    final var user = userLoginRepository.findByServiceId(loginRequest.serviceId())<br>        .orElseThrow(() -&gt; new CriticalException(&quot;User not found&quot;));<br>    if (!user.getOtp().equalsIgnoreCase(loginRequest.pin())) {<br>      throw new CriticalException(&quot;Incorrect OTP&quot;);<br>    }<br>    if (!user.isRememberLevelup()) {<br>      final var token = createToken(user);<br>      final var detail = Detail.builder()<br>          .token(token)<br>          .availableTypes(user.getLevelUp())<br>          .build();<br>      return TwoFactorAuthentication.builder()<br>          .id(Utility.generateUUID())<br>          .code(&quot;app.security.authentication.acr.level&quot;)<br>          .severity(&quot;WARN&quot;)<br>          .timestamp(new Date().toString())<br>          .retryable(false)<br>          .details(List.of(detail))<br>          .build();<br>    }<br>    return createToken(user);<br>  }<br><br>  private CreateOtpSessionResult createOtpSessionByEmail(final LoginRequest loginRequest) {<br>    final var user = userLoginRepository.findByServiceId(loginRequest.serviceId())<br>        .orElseThrow(() -&gt; new CriticalException(&quot;User not found&quot;));<br>    if (!user.getOtp().equalsIgnoreCase(loginRequest.pin())) {<br>      throw new CriticalException(&quot;Incorrect OTP&quot;);<br>    }<br>    return createToken(user);<br>  }<br>}</pre><p>Controller</p><pre>import io.swagger.annotations.Api;<br>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.*;<br><br><br>@RestController<br>@CrossOrigin<br>@RequestMapping(&quot;/v1/api&quot;)<br>@Slf4j<br>@RequiredArgsConstructor<br>public class LoginAPI {<br><br>    private final LoginService loginService;<br><br>    @PostMapping(&quot;/login&quot;)<br>    public ResponseEntity&lt;Object&gt; createSession(@RequestBody LoginRequest loginRequest) {<br>        log.info(&quot;Request : {}&quot;, loginRequest);<br>        return loginService.createSession(loginRequest);<br>    }<br><br>    @PostMapping(&quot;/otp&quot;)<br>    public ResponseEntity&lt;Object&gt; createEmailSession(@RequestBody LoginRequest loginRequest, @RequestHeader(required = false, name = &quot;authorization&quot;) String token) {<br>        log.info(&quot;Request : {}&quot;, loginRequest);<br>        return loginService.createEmailSession(token, loginRequest);<br>    }<br><br>    @PostMapping(&quot;/pin&quot;)<br>    public ResponseEntity&lt;Object&gt; createOtpSession(@RequestBody LoginRequest loginRequest) throws Exception {<br>        log.info(&quot;Request : {}&quot;, loginRequest);<br>        return loginService.createOtpSession(loginRequest);<br>    }<br>}</pre><p>Java 17 code for Controller</p><pre>@RestController<br>@CrossOrigin<br>@RequestMapping(&quot;/v1/api&quot;)<br>@Slf4j<br>@RequiredArgsConstructor<br>public class LoginAPI {<br><br>    private final LoginService loginService;<br><br>    @PostMapping(&quot;/login&quot;)<br>    public ResponseEntity&lt;? extends SessionResult&gt; createSession(@RequestBody final LoginRequest loginRequest) {<br>    log.info(&quot;Request : {}&quot;, loginRequest);<br>    final var createSessionResult = loginService.createSession(loginRequest);<br>    return switch (createSessionResult.getClass().getSimpleName()) {<br>      case &quot;Token&quot; -&gt; new ResponseEntity&lt;&gt;(createSessionResult, OK);<br>      case &quot;Error&quot; -&gt; new ResponseEntity&lt;&gt;(createSessionResult, UNPROCESSABLE_ENTITY);<br>      default -&gt; throw new CriticalException(&quot;Please check some internal issue happened&quot;);<br>    };<br>  }<br><br>    @PostMapping(&quot;/pin&quot;)<br>    public ResponseEntity&lt;? extends OtpSessionResult&gt; createOtpSession(@RequestBody final LoginRequest loginRequest) {<br>         log.info(&quot;Request : {}&quot;, loginRequest);<br>         final var createOtpSessionResult = loginService.createOtpSession(loginRequest);<br>         return switch (createOtpSessionResult.getClass().getSimpleName()) {<br>                         case &quot;Token&quot; -&gt; new ResponseEntity&lt;&gt;(createOtpSessionResult, OK);<br>                         case &quot;TwoFactorAuthentication&quot; -&gt; new ResponseEntity&lt;&gt;(createOtpSessionResult, UNPROCESSABLE_ENTITY);<br>                         default -&gt; throw new CriticalException(&quot;Please check some internal issue happened&quot;);<br>           }<br>    }<br>}</pre><h4>Conclusion: Crafting Code as an Art Form</h4><p>Java 17’s sealed classes and records aren’t just features; they’re tools for crafting code as an art form. Embrace the simplicity, harness the power, and let your code resonate with the elegance of a well-composed symphony.</p><p>So, raise the curtain, let the show begin, and code on with Java 17!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89bcf28a636f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unveiling the Power of Java 17: Sealed Classes vs Enums]]></title>
            <link>https://medium.com/@priyankapruthe/unveiling-the-power-of-java-17-sealed-classes-vs-enums-d27840aefbbe?source=rss-95172fd0035f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d27840aefbbe</guid>
            <dc:creator><![CDATA[priyanka pruthi]]></dc:creator>
            <pubDate>Tue, 02 Jan 2024 14:56:56 GMT</pubDate>
            <atom:updated>2024-01-02T15:08:29.503Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*Ads_Pv3LAKaZ2MHJBOWhZQ.png" /></figure><p>🚀 Java 17 has ushered in a new era of language enhancements, and two standout features stealing the spotlight are sealed classes and enums. Let’s embark on a journey to explore these game-changers, understand their strengths, and uncover when to wield each for maximum impact.</p><h4>Sealed Classes: The Architects of Controlled Hierarchies</h4><p>🧱 <strong>Building Block</strong>: Sealed classes introduce a new level of control over class hierarchies. Picture this — you decide which subclasses are allowed, enhancing clarity, maintainability, and yes, adding a layer of security.</p><p>🎨 <strong>Explicit Elegance</strong>: Sealed classes proudly declare their allowed subclasses using the “permits” keyword.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2_A0vs4dMU966uPC1VmqBQ.png" /></figure><p>🌟 <strong>Pattern Magic</strong>: Enhanced switch expressions and pattern matching dance seamlessly with sealed classes, making your code a joy to read and maintain. No requirement of using instanceof operator to check instance type</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rbwZ9PuGPzIGSVYtBATPzQ.png" /></figure><p>📜 <strong>Improved Readability</strong>: Sealed classes bring elegance and readability to your code by showcasing the permissible subclasses right in the class declaration.</p><p>🛡️ <strong>Enhanced Security:</strong> By restraining possible subclasses, sealed classes boost security, reducing the chances of unintended or malicious extensions.</p><p><strong>Ideal Playgrounds for Sealed Classes</strong>:</p><ul><li><strong>Frameworks &amp; Libraries</strong> 🛠️ : Ideal for frameworks where a specific set of subclasses is expected, ensuring a stable and controlled API.</li><li><strong>Domain Models</strong> 🏰 : Perfect for domain models with a fixed set of entities, providing clarity in representing allowable types.</li><li><strong>Pattern Matching Galore</strong> 🔄 : Essential for scenarios requiring complex logic based on the type of an object.</li></ul><h4>Enums: The Constants Maestros</h4><p>🌈 <strong>Coloring Constants</strong>: Enums, the old guards of Java, represent a fixed set of named values. Elegant and timeless, they bring a touch of color to your code with their defined constants.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qdrMesFlG2e8hzZt2-N00A.png" /></figure><p>🤝 <strong>Singleton Allies</strong>: Need a singleton? Enums got your back. They effortlessly implement the singleton pattern, ensuring there’s only one instance available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CF-jefnipgf1RQVSA23qgw.png" /></figure><p>🎭 <strong>Versatile Performers</strong>: Enums not only define constants but also come with methods, providing a symphony of functionality with each constant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vE2s8_Z2SCLlWCIolcHaNg.png" /></figure><p>↔️ <strong>Switch Statements: </strong>Enums play harmoniously with switch statements, making code more readable and error-resistant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ixmPajT3brrxesRriJPCw.png" /></figure><p><strong>Ideal Playgrounds for</strong> <strong>Enums</strong>:</p><ul><li><strong>Constants Extravaganza</strong> 🎭 : Perfect for representing a fixed set of constants with equal importance.</li><li><strong>Singleton Spotlight</strong> 🌟 : When a simple implementation of the singleton pattern is all you need, enums deliver.</li><li><strong>Readability Oasis</strong> 📖 : For scenarios where simplicity and readability are paramount, especially with constant</li></ul><h4><strong>Sealed Classes vs Enums: A Comparison</strong></h4><h4><strong>Common Characteristics:</strong></h4><ol><li><strong>Fixed Set of Instances:<br> </strong>Both sealed classes and enums represent a fixed set of instances, restricting the number of possible values.</li><li><strong>Improved Code Readability:<br> </strong>Both features enhance code readability by clearly defining a set of related constants or classes.</li></ol><h4><strong>Differences:</strong></h4><p>1.<strong>Extensibility</strong>:<br> Sealed classes offer more flexibility in terms of extensibility. You can add new subclasses within the same package or module, providing a level of control over the hierarchy. Enums, on the other hand, are inherently closed and cannot be extended.</p><p>2. <strong>Singleton Pattern:</strong><br> Enums automatically follow the singleton pattern, ensuring that only one instance of each constant exists. Sealed classes do not enforce this pattern, allowing multiple instances of subclasses.</p><p>3. <strong>Switch Statements:</strong><br> While both sealed classes and enums work well with switch statements, enums provide a more concise syntax, especially when each constant requires unique behavior.</p><p>4. <strong>Hierarchy Structure:</strong><br> Sealed classes allow a more complex hierarchy with multiple levels of subclasses, offering a fine-grained control over the structure. Enums, by design, have a flat structure with no subclassing.</p><h4>Choosing Your Java Superpower</h4><h4>Sealed Classes: When Precision Matters ⚔️</h4><p>🎢 <strong>Classy Complexity</strong>: Sealed classes take the stage when your class hierarchy gets intricate, especially when subclasses might have their subclasses.</p><p>🕵️ <strong>Pattern Match Detectives</strong>: If your code craves pattern matching and enhanced switch expressions, sealed classes deliver an expressive solution.</p><p>🏰 <strong>Framework Flourish</strong>: For frameworks or libraries demanding a specific set of subclasses, sealed classes ensure a well-defined and controlled extension mechanism.</p><h4>Enums: When Simplicity Sings 🎶</h4><p>🚀 <strong>Constant Constellations</strong>: Enums shine in scenarios where a fixed set of constants takes center stage, each holding its own significance.</p><p>💡 <strong>Singleton Harmony</strong>: When a single instance steals the show, enums craft a melody of simplicity and thread safety.</p><p>📜 R<strong>eadability Symphony</strong>: For scenarios where simplicity and readability are paramount, enums compose an elegant symphony.</p><h4>Closing Notes: Java 17, Your Creative Canvas 🎨</h4><p>Java 17 opens up a realm of possibilities, and the choice between sealed classes and enums is your artistic decision. Consider the complexity of your hierarchies, the need for pattern magic, and the elegance you seek. With sealed classes and enums, Java 17 empowers you to create a masterpiece tailored to your project’s unique needs. 🚀✨</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d27840aefbbe" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>