<?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 Manoj Suthar on Medium]]></title>
        <description><![CDATA[Stories by Manoj Suthar on Medium]]></description>
        <link>https://medium.com/@manoj-suthar?source=rss-16315cba8b13------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*own6Uo4rWKeSuvkpzUB6vA.jpeg</url>
            <title>Stories by Manoj Suthar on Medium</title>
            <link>https://medium.com/@manoj-suthar?source=rss-16315cba8b13------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 04:10:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@manoj-suthar/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[Structured Concurrency in Java]]></title>
            <link>https://manoj-suthar.medium.com/structured-concurrency-in-java-b1db5c5bdf4a?source=rss-16315cba8b13------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1db5c5bdf4a</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[threads]]></category>
            <dc:creator><![CDATA[Manoj Suthar]]></dc:creator>
            <pubDate>Sun, 29 Oct 2023 19:47:51 GMT</pubDate>
            <atom:updated>2023-10-29T19:47:51.517Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Java 19 will introduce the incubating Structured Concurrency project (JEP 428). As the name suggests, the project will add structured concurrency capabilities to Java. This post will walk through how to use the new APIs for handling multithreaded code.</p><h3>Why use structured concurrency?</h3><p>When you create a new Thread in Java, a system call is done to the OS, telling it to create a new system thread. Creating a system thread is expensive because the call takes up much time, and each thread takes up some memory. Your threads also share the same CPU, so you don’t want them to block it, causing other threads to wait unnecessarily.</p><p>You can use asynchronous programming to prevent this from happening. You start a thread and tell it what to do when the data arrives. Until the data is available, other threads can use the CPU recourses for their task. In the example below, we use the CompletableFuture to get some data and tell it to print it to the console when the data is available.</p><pre>CompletableFuture.supplyAsync(() -&gt; &quot;some data&quot;)<br>                .thenAccept(System.out::println);</pre><p>Asynchronous programming works fine, but there is another way to work and think about concurrency, called structured concurrency. Structured concurrency is a Java enhancement proposal (JEP) for developing concurrent applications. It aims to make it easier to write and debug multithreaded code in Java.</p><h3>What is structured concurrency</h3><p>With JEP 428, we get a “Structured concurrency” model to work with and think about threads. The idea behind structured concurrency is to make the lifetime of a thread work the same as code blocks in structured programming. For example, in a structured programming language like Java, If you call method <strong>B</strong> inside method <strong>A</strong> then method <strong>B</strong> must be finished before you can exit method <strong>A</strong>. The lifetime of method <strong>B</strong> can’t exceed that of method <strong>A</strong>.</p><p>With Structured concurrency, we want the same kind of rules as with structured programming. When you create virtual thread <strong>X</strong> inside virtual thread <strong>Y</strong>, the lifetime of thread <strong>X</strong> can’t exceed that of thread <strong>Y</strong>. Structured concurrency makes working and thinking about threads a lot easier. For example, when you stop parent thread <strong>Y</strong>, all its child threads will also be cancelled, so you don’t have to be afraid of runaway threads still running. The crux of the pattern is to avoid fire and forget concurrency.</p><p>Thread YThread XStart thread XPerform workPerform workDone!Thread Y is finishedbecause its work andThreads X work is doneThread YThread X</p><p>Thread Y starts a new thread X; both work separately from each other, but before thread Y can finish, it has to wait for thread X to have completed its work. Let’s see what that looks like in Java!</p><h3>Invoke all pattern — with structured concurrency</h3><p>Structured concurrency binds the lifetime of threads to the code block which created them. The binding is done by using the StructuredTaskScope inside a try-with-recourses. In this try, you have a scope object you use to fork new child threads.</p><p>In the example below, we create a scope using new StructuredTaskScope.ShutdownOnFailure(). This type of scope shutdowns every running child thread if one of them throws an exception during execution. We will only get a result when all the created child threads finish successfully. This behaviour looks similar to the invokeAll method of the ExecutorService.</p><pre>String getDog() throws ExecutionException, InterruptedException {<br>    try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {<br>        Future&lt;String&gt;  name  = scope.fork(this::getName);<br>        Future&lt;String&gt; breed = scope.fork(this::dogBreed);<br>        scope.join();<br>        scope.throwIfFailed();<br>        return &quot;it&#39;s name is:&quot; + name.resultNow() + &quot;, and is a &quot; + breed.resultNow();<br>    }<br>}<br>String getName(){return &quot;Max&quot;;}<br>String dogBreed(){return &quot;Golden retriever&quot;;}</pre><h3>Invoke any pattern — with structured concurrency</h3><p>Unlike the Invoke all pattern that waits for every child thread to finish. Instead, the invoke any pattern will return the result of the first thread to finish and shut down the remaining child threads. The example below looks similar to the previous one with some subtle changes. Now we initiate the StructuredTaskScope like this new StructuredTaskScope.ShutdownOnSuccess&lt;String&gt;(), and we don&#39;t create holders for future references.</p><p>Only after calling scope.join() we can get the result of the first finished thread by calling scope.result(). The example below will return “result: Golden retriever”.</p><pre>String getDog() throws ExecutionException, InterruptedException {<br>    try (var scope = new StructuredTaskScope.ShutdownOnSuccess&lt;String&gt;()) {<br>        scope.fork(this::getName);<br>        scope.fork(this::dogBreed);<br>        scope.join();<br>        return &quot;result: &quot; + scope.result();<br>    }<br>}<br>String getName() throws InterruptedException {<br>    Thread.sleep(5000);<br>    return &quot;Max&quot;;<br>}<br>String dogBreed(){return &quot;Golden retriever&quot;;}</pre><h3>Exceptions and structured concurrency</h3><p>We will look back at the example of the Invoke all pattern to see what happens when an exception is thrown. The second child thread that retrieves the dog’s breed will throw an exception while the first child thread is still running. When the exception is thrown, the StructuredTaskScope will shut down every child thread it has created. To get the underlying exception, you must call the throwIfFailed() method on your scope object. Please remember that you can only call throwIfFailed() after you call join().</p><p>If you don’t call the throwIfFailed() method, the exception you will see in the console will be an IllegalStateException. This is confusing because we throw a RuntimeException() in the dogBreed method. You need to call the throwIfFailed method to show the RuntimeException in the console.</p><pre>String getDog() throws ExecutionException, InterruptedException {<br>    try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {<br>        Future&lt;String&gt;  name  = scope.fork(this::getName);<br>        Future&lt;String&gt; breed = scope.fork(this::dogBreed);<br>        scope.join();<br>        scope.throwIfFailed();<br>        return &quot;it&#39;s name is:&quot; + name.resultNow() + &quot;, and is a &quot; + breed.resultNow();<br>    }<br>}<br>String getName() throws InterruptedException {<br>    Thread.sleep(5000);<br>    return &quot;Max&quot;;<br>}<br>String dogBreed(){<br>    throw new RuntimeException();<br>}</pre><h3>Conclusion</h3><p>This post looked at the benefits of structured concurrency to the Java language and how it is implemented in Java 19 EA with JEP 428. We went over how to create different kinds of scopes for threads and what happens when one of the virtual threads in a scope throws an error.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1db5c5bdf4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microservices Deployment Models]]></title>
            <link>https://manoj-suthar.medium.com/microservices-deployment-models-6f480cdd1857?source=rss-16315cba8b13------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f480cdd1857</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Manoj Suthar]]></dc:creator>
            <pubDate>Thu, 29 Jun 2023 13:34:50 GMT</pubDate>
            <atom:updated>2023-06-29T13:34:50.359Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s understand a few different ways that microservices are deployed.</p><p>Microservices are a popular architectural pattern for building large-scale, complex applications. They provide a way to break down a monolithic application into smaller, more manageable services that can be developed, tested, and deployed independently. There are several ways to deploy microservices, each with their own advantages and disadvantages. In this article, we will explore some of the most common deployment strategies for microservices.</p><p><strong>Containerization</strong> <br>Containerization is a popular way to deploy microservices. It involves packaging each microservice as a self-contained unit with all its dependencies, libraries, and configuration files, into a container image. Containerization allows microservices to be deployed independently of each other and in a scalable way. You can use containerization platforms such as Docker and Kubernetes to deploy and manage your microservices.</p><p>In this approach, each microservice is packaged as a container image that contains all the necessary code and dependencies. The container images can then be deployed to a container orchestration platform, such as Kubernetes or Docker Swarm, which manages the container instances and their communication with each other. Containerization provides an efficient way to manage microservices at scale, as containers can be easily replicated and deployed across multiple nodes. Containerization also enables fast and reliable deployment, as containers can be easily rolled back or updated.</p><p><strong>Self-Contained Microservices</strong><br>Self-contained microservices are one of the most common ways to deploy microservices. In this approach, each microservice is packaged as a self-contained unit that contains all the necessary code and dependencies to run independently. Each microservice is deployed on its own virtual machine, container, or server. This approach provides maximum isolation and autonomy for each microservice, as they can be developed and deployed independently of one another. However, managing a large number of microservices can become challenging, and the infrastructure costs can be high.</p><p><strong>Serverless Computing</strong><br>Serverless computing allows you to deploy your microservices without worrying about the underlying infrastructure. In serverless computing, you upload your code to a cloud provider&#39;s serverless platform, and the provider takes care of scaling, provisioning, and managing the infrastructure. Serverless computing platforms such as AWS Lambda, Google Cloud Functions, and Azure Functions provide an easy way to deploy microservices without worrying about infrastructure.</p><p>Serverless computing is a newer approach to microservices deployment that has gained popularity in recent years. In this approach, microservices are deployed as functions that are executed on demand in a serverless environment, such as AWS Lambda or Azure Functions. Serverless computing eliminates the need for managing infrastructure, as the cloud provider manages the underlying servers and resources. This approach provides maximum scalability and cost-effectiveness, as you only pay for the computing resources you use. However, serverless computing may not be suitable for all types of microservices, as it imposes some limitations on the execution environment and may not be compatible with certain types of applications.</p><p><strong>Virtual Machines </strong><br>Virtual machines (VMs) provide another way to deploy microservices. In this approach, you install the microservices on a virtual machine that runs on a host operating system. VMs allow you to isolate your microservices and run multiple services on a single machine. However, VMs can be more resource-intensive than containerization, and they may not be as flexible and scalable.</p><p><strong>Cloud-Native Deployment </strong><br>Cloud-native deployment is an approach that leverages cloud-native technologies and architectures to deploy microservices. Cloud-native deployment involves using technologies such as containers, container orchestration platforms, service meshes, and API gateways to build and deploy microservices. Cloud-native architectures provide scalability, resilience, and flexibility, making them a popular choice for deploying microservices.</p><p><strong>Service Mesh</strong><br>A service mesh is a dedicated infrastructure layer for managing service-to-service communication within a microservices architecture. In this approach, each microservice communicates with other microservices through a dedicated proxy, which provides advanced networking features such as load balancing, service discovery, and traffic management. Service meshes can be deployed as a sidecar container alongside each microservice, or as a dedicated infrastructure layer that sits between the microservices and the outside world. Service meshes provide a way to manage microservices communication in a more efficient and secure way, but can add complexity to the architecture and require additional resources to operate.</p><p><strong>Hybrid Deployment </strong><br>You can also use a combination of the above deployment options to deploy your microservices. For example, you can use containerization for some microservices and serverless computing for others. Hybrid deployment allows you to take advantage of the strengths of each deployment option and provides flexibility in deploying your microservices.</p><p>Hybrid deployment is a deployment strategy that combines multiple approaches to deploying microservices. For example, you might deploy some microservices as self-contained units on virtual machines, while deploying others as containerized images on a container orchestration platform. Hybrid deployment provides flexibility and enables you to choose the deployment strategy that best suits the needs of each microservice. However, hybrid deployment can also add complexity to the architecture, as you need to manage multiple deployment strategies simultaneously.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f480cdd1857" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Kafka Key Components]]></title>
            <link>https://manoj-suthar.medium.com/apache-kafka-key-components-de26e812f9d2?source=rss-16315cba8b13------2</link>
            <guid isPermaLink="false">https://medium.com/p/de26e812f9d2</guid>
            <category><![CDATA[event-streaming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[kafka-streams]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Manoj Suthar]]></dc:creator>
            <pubDate>Wed, 07 Jun 2023 19:20:08 GMT</pubDate>
            <atom:updated>2023-06-07T19:22:44.356Z</atom:updated>
            <content:encoded><![CDATA[<ul><li><strong>What is Apache kafka</strong></li></ul><p>It is an opensource distributed system consisting of servers and clients. Apache Kafka is used primarily to build realtime data streaming pipelines.</p><p>Apache Kafka is used by thousands of the world’s leading organizations for high performance data pipelines, streaming analytics, data integration and many other vital applications.</p><ul><li><strong>Use Cases of Apache kafka</strong></li></ul><p>The use cases of Apache Kafka are many. These include stream processing for different business applications. Apache Kafka makes up the storage mechanism for some of the prominent stream processing frameworks.</p><ol><li>Messaging systems</li><li>Activity Tracking</li><li>Gather metrics from many different locations, for example, IoT device</li><li>Application logs analysis</li><li>Decoupling of system dependencies</li><li>Integration with Big Data technologies like Spark, Flink, Storm, Hadoop.</li><li>Eventsourcing store</li></ol><ul><li><strong>Kafka Topics</strong></li></ul><p>Similar to how databases have tables to organize and segment datasets, Kafka uses the concept of topics to organize related messages.</p><ul><li><strong>Kafka Partitions</strong></li></ul><p>Topics are broken down into a number more than of partitions. A single topic may have one partition</p><ul><li><strong>Kafka Producers</strong></li></ul><p>Applications that send data into topics are known as Kafka producers. Applications typically integrate a Kafka client library to write to Apache Kafka . Excellent client libraries exist for almost programming languages that are popular today including Python, Java, Go all , and others.</p><ul><li><strong>Message Keys</strong></li></ul><p>Each event message contains an optional key and a value.</p><ul><li><strong>Kafka Consumers</strong></li></ul><p>Applications that read data from Kafka topics are known as consumers. Consumers can read from one or more partitions at a time in Apache Kafka.</p><ul><li><strong>Kafka Consumer Groups</strong></li></ul><p>Consumers that are part of the same application and therefore performing the same &quot;logical job&quot; can be grouped together as a Kafka consumer group.</p><ul><li><strong>Kafka Consumer Offsets</strong></li></ul><p>Kafka brokers use an internal topic named given __ consumer_offsets consumer group that keeps track of what messages a last successfully processed.</p><ul><li><strong>Kafka Broker</strong></li></ul><p>A single Kafka server is called a Kafka Broker. That Kafka broker is a program that runs on the Java Virtual Machine (Java version 11+) and usually a server that is meant to be a Kafka broker will solely run the necessary program and nothing else.</p><ul><li><strong>Bootstrap Server</strong></li></ul><p>A client that wants to send or receive messages from the Kafka cluster the cluster. may connect to any broker in Every broker in the cluster has metadata about all the other brokers and will help the client connect to them as well, and therefore any broker in the cluster is also called a bootstrap server.</p><ul><li><strong>Kafka Topic Replication</strong></li></ul><p>One of the main reasons for Kafka’s popularity, is the resilience it offers in the face of broker failures. Machines fail, and often we cannot predict when that is going to happen or prevent it. Kafka is designed with replication as a core feature to withstand these failures while maintaining uptime and data accuracy.</p><ul><li><strong>InSync Replicas (ISR)</strong></li></ul><p>One of the main reasons for Kafka’s popularity, is the resilience it offers in the face of broker failures. Machines fail, and often we cannot predict when that is going to happen or prevent it. Kafka is designed with replication as a core feature to withstand these failures while maintaining uptime and data accuracy.</p><p>Resources:</p><ul><li><a href="https://kafka.apache.org/">https://kafka.apache.org/</a></li><li><a href="https://www.confluent.io/">https://www.confluent.io/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de26e812f9d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>