<?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[art of coding - Medium]]></title>
        <description><![CDATA[the perfect blog for beginners - Medium]]></description>
        <link>https://medium.com/art-of-coding?source=rss----ed8b09a8a1de---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>art of coding - Medium</title>
            <link>https://medium.com/art-of-coding?source=rss----ed8b09a8a1de---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 02:12:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/art-of-coding" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Scaling from Zero to Millions of users (part-1)]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/art-of-coding/scaling-from-zero-to-millions-of-users-eeabe08ed921?source=rss----ed8b09a8a1de---4"><img src="https://cdn-images-1.medium.com/max/973/1*2GVzHOGGQiGylG0OTWGVrw.png" width="973"></a></p><p class="medium-feed-snippet">Scaling a system from zero to one million users is a continuous journey.</p><p class="medium-feed-link"><a href="https://medium.com/art-of-coding/scaling-from-zero-to-millions-of-users-eeabe08ed921?source=rss----ed8b09a8a1de---4">Continue reading on art of coding »</a></p></div>]]></description>
            <link>https://medium.com/art-of-coding/scaling-from-zero-to-millions-of-users-eeabe08ed921?source=rss----ed8b09a8a1de---4</link>
            <guid isPermaLink="false">https://medium.com/p/eeabe08ed921</guid>
            <dc:creator><![CDATA[Chinmay Venkata Sabbam]]></dc:creator>
            <pubDate>Sat, 04 Jul 2026 08:11:50 GMT</pubDate>
            <atom:updated>2026-07-04T11:38:28.390Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[No Locks,No Leader: How Rendezvous Hashing powers a Distributed scheduled Jobs framework]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/art-of-coding/no-locks-no-leader-how-rendezvous-hashing-powers-a-distributed-scheduled-jobs-framework-c21f134103e3?source=rss----ed8b09a8a1de---4"><img src="https://cdn-images-1.medium.com/max/600/1*RedHYeRrArTYmz-PNGk2zg.png" width="600"></a></p><p class="medium-feed-snippet">A production walk-through of assigning M jobs across N workers &#x2014; without zookeeper, etcd or distributed locks.</p><p class="medium-feed-link"><a href="https://medium.com/art-of-coding/no-locks-no-leader-how-rendezvous-hashing-powers-a-distributed-scheduled-jobs-framework-c21f134103e3?source=rss----ed8b09a8a1de---4">Continue reading on art of coding »</a></p></div>]]></description>
            <link>https://medium.com/art-of-coding/no-locks-no-leader-how-rendezvous-hashing-powers-a-distributed-scheduled-jobs-framework-c21f134103e3?source=rss----ed8b09a8a1de---4</link>
            <guid isPermaLink="false">https://medium.com/p/c21f134103e3</guid>
            <dc:creator><![CDATA[Chinmay Venkata Sabbam]]></dc:creator>
            <pubDate>Fri, 19 Jun 2026 08:57:57 GMT</pubDate>
            <atom:updated>2026-06-19T10:32:58.346Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Observer Design pattern]]></title>
            <link>https://medium.com/art-of-coding/observer-design-pattern-711439009603?source=rss----ed8b09a8a1de---4</link>
            <guid isPermaLink="false">https://medium.com/p/711439009603</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[design-thinking]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Chinmay Venkata Sabbam]]></dc:creator>
            <pubDate>Thu, 01 Jun 2023 00:36:10 GMT</pubDate>
            <atom:updated>2023-06-01T00:36:10.404Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SYA7mEok8E727Zv--r4_6g.jpeg" /></figure><p>Just Imagine we are working in a monitoring-based company. we have a monitoring tool that receives data from various external devices.</p><h3>Requirement</h3><p>For that received data from various devices, we need to create different views and users should have the flexibility to add and remove the views at any point in time. Initially, we have three views.</p><ol><li>Metric Processing</li><li>Synthetic Monitoring</li><li>Alert Processing</li></ol><h3>Initial Design</h3><p>Initially, we come up with the below-mentioned design</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*k11b7lm_8-hoi-hyQvNmuA.png" /><figcaption>Initial Design</figcaption></figure><p><strong>Let&#39;s Analyze the drawbacks of our Initial Design</strong>:</p><p>To Add or Remove any View (For add or Remove the concrete classes of the create view Interface) we need to Touch the Metric Data class. It will create two problems.</p><ol><li>There is a tight coupling between the Views and Metric Data classes. Let&#39;s Imagine In the future User will create 1000 views, it is very difficult to maintain the code</li><li>what if we need to add the views during Runtime, This looks hard coded.</li></ol><h3>Final Design</h3><p>To overcome the above problems, we brainstorm and will decide to Implement the Observer Design Pattern.</p><h3>Observer Design Pattern</h3><p>The observer design pattern works like the publisher + subscribers model.</p><p>For Example, if you take a subscription to our blog, if any new posts are published, you will be notified, if you unsubscribe, you will not be notified. Similarly, the Observer pattern works.</p><p>Here we are notified as Subject (Blog writer) and you will be notified as Observer (Subscriber).</p><p>Let&#39;s discuss how we apply this Observer design pattern for our monitoring application.</p><p>Metric Data is the Subject, views are the Observers</p><p>we can add and remove the Observer at any point in time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3HHjH53GmK_TU4ahpcTfOQ.png" /><figcaption>Final Implementation</figcaption></figure><p>In the above design, we observed below points</p><h3>Oops Basics covered in this design</h3><ol><li>Inheritance</li></ol><pre>public class MetricProcessing implements View, Observer {<br><br>}</pre><p>Abstraction And Encapsulation</p><pre>private static List&lt;Observer&gt; observers = new ArrayList&lt;&gt;();</pre><h3>Oops principles covered in this design</h3><ul><li><strong>Encapsulate what varies</strong></li></ul><p>In this pattern state of the subject and the number of observers always change, we can vary the number of observers without changing the Subject. In this application, every time we are receiving new metric data and we can capable to create a more number of views without changing the Metric Data</p><ul><li><strong>Favorable Composition Over inheritance</strong></li></ul><p>we can capable to compose any number of observers, they can be set up even at runtime</p><ul><li><strong>Program to interfaces, not for Implementations</strong></li></ul><p>In this pattern, the Subject is the Interface and Observer is the Interface. The subject can keep track of all Observers by adding, removing and notifying</p><blockquote><strong>Observer design pattern defines a one-to-many relationship dependency between objects, If the state changes in Subject, it notified to all its dependents and they are loosely coupled</strong></blockquote><p><strong>CODE FOR COMPLETE IMPLEMENTATION</strong>:</p><p><a href="https://github.com/venkatchinmay/design_patterns/tree/master/src/main/java/org/observerdesignpattern">Complete code implementation for the above-mentioned design</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=711439009603" width="1" height="1" alt=""><hr><p><a href="https://medium.com/art-of-coding/observer-design-pattern-711439009603">Observer Design pattern</a> was originally published in <a href="https://medium.com/art-of-coding">art of coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Strategy design pattern]]></title>
            <link>https://medium.com/art-of-coding/strategy-design-pattern-2671d79531e7?source=rss----ed8b09a8a1de---4</link>
            <guid isPermaLink="false">https://medium.com/p/2671d79531e7</guid>
            <category><![CDATA[design-thinking]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Chinmay Venkata Sabbam]]></dc:creator>
            <pubDate>Sun, 21 May 2023 02:44:08 GMT</pubDate>
            <atom:updated>2023-05-21T02:44:08.369Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*9fStl3ImbO9PfHkzQa6dnw.jpeg" /></figure><p>Let&#39;s Imagine we are in the Car Development Software Company and we are having Car Company initial Design like this</p><h3>Initial Design of the Software</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*_LT4Z0jV13vaxNMrSmHHog.png" /><figcaption>initial design of the software</figcaption></figure><p>we implemented the all features of the car like fuel, engine, tyres and headlamps etc ....</p><p>Later Board Members Decided to implement the new feature &quot;<strong>Auto gear</strong>&quot; which is a highly demandable feature in the market and ask Managers to implement it in the software and come with Demo within one week.</p><p>Managers assigned this task to one of the developers to implement the &quot;<strong>Auto gear</strong>&quot; feature. Developer Said that I am an OOps programmer and I will Implement this feature within an hour and come up with a design like this</p><h3>Initial Implementation of Auto Gear:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*jJxu_VtXrQFoMAZotf2_Bw.png" /><figcaption>addition of auto gear feature</figcaption></figure><p>The manager start giving a demo in front of the Board members and they were surprised that <strong>Ambassador</strong> and <strong>Alto</strong> had an <strong>Auto gear</strong> Feature they decided that we can&#39;t afford this feature in these cars and asked the manager to remove the Auto gear feature in these cars.</p><p>The manager asked the developer to remove the &quot;Auto <strong>gear</strong> feature in <strong>Ambassador</strong> and <strong>Alto</strong> cars.</p><p>Developer thinking that how to remove the <strong>Auto gear</strong> feature in <strong>Ambassador</strong> and <strong>Alto</strong> cars, Since he is an OOps programmer, <strong>overriding the isAutoGear() method</strong> will solve the problem.</p><p>During this Implementation process, Board members decided to implement <strong>different kinds of engines in different cars</strong>. when engines are different than automatically <strong>fuels are also different</strong> and ask the manager and developer to implement the same in the software.</p><p>The developer taught that specs are changing in every board meeting and he comes with a design like this</p><h3>Design with Interfaces</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*4qE_Hp7FxRFzfk3f5jY0MQ.png" /><figcaption>with interfaces design</figcaption></figure><p>The developer brings this design to the manager to review. The manager asked the Developer, <strong>Is it a perfect design to Implement our specs?</strong></p><p><strong>what is your taught process on this ..... Is there any drawback to the above design?</strong></p><h3>Drawbacks of above design</h3><p><strong>Imagine we have 100 car types Instead of 4 in the future</strong> we need to <strong>override</strong> Engine, Gear and Fuel Interface methods in every class, which causes</p><ul><li>Duplicate code across sub classes</li><li>If something changes, we need to change in every class, huge chances to get issues.</li><li>Maintaining code is very difficult</li><li>Hard to gain knowledge over Car behaviors and Run time changes are also difficult.</li></ul><h3>Strategy pattern</h3><p>Later Developer made a brainstorm and observed what are the specs <strong>frequently changing and noted their behaviors</strong> and he also observed what are <strong>specs not changing</strong> in Car and he made a list like this</p><ul><li><strong>changed specs</strong> :</li></ul><ol><li>engine</li><li>fuel</li><li>gear</li></ol><ul><li><strong>unchanged specs</strong> :</li></ul><ol><li>tyres</li><li>headlamps</li></ol><p>and <strong>he encapsulated the changed specs in the Car class</strong> and made a final design like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NTd2ZkDrjRerFUOIA0hADQ.png" /><figcaption>strategy pattern design</figcaption></figure><blockquote><strong>&quot;Observed the behavior of the class and Encapsulate what is changing frequently. This pattern is called strategy pattern&quot;</strong></blockquote><h3>Object-oriented basics covered in this pattern</h3><ul><li>Abstraction</li><li>Encapsulation</li><li>Polymorphism</li><li>Inheritance</li></ul><h3>Object-oriented principles we followed in this pattern</h3><ul><li>Encapsulate what varies</li><li>Favorable Composition Over inheritance</li><li>Program to interfaces, not for Implementations</li></ul><pre>//encapsulation and abstraction and Program to interfaces<br>    private Engine engine ;<br>    private Fuel fuel;<br>    private Gear gear;<br><br>    // polymorphism<br>        Engine engine = new SimplePetrolEngine();<br>        setEngine(engine);<br>        Fuel fuel = new Petrol();<br>        setFuel(fuel);<br>        Gear gear = new NormalGear();<br>        setGear(gear);</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2671d79531e7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/art-of-coding/strategy-design-pattern-2671d79531e7">Strategy design pattern</a> was originally published in <a href="https://medium.com/art-of-coding">art of coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Micro Services and its Constraints]]></title>
            <link>https://medium.com/art-of-coding/micro-services-and-its-constraints-f16fd8beffbc?source=rss----ed8b09a8a1de---4</link>
            <guid isPermaLink="false">https://medium.com/p/f16fd8beffbc</guid>
            <category><![CDATA[operations]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Chinmay Venkata Sabbam]]></dc:creator>
            <pubDate>Tue, 01 Feb 2022 07:40:40 GMT</pubDate>
            <atom:updated>2022-02-01T07:40:40.573Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8R_hEnLPRjwphwl2XFesfw.png" /></figure><p>Before we going to understand the microservices, we need to understand the monolith architecture</p><h3>Monolith architecture</h3><ol><li>Monolith Components are <strong><em>tightly coupled</em></strong></li><li>In Monolith, <strong><em>Components are developed, deployed and managed as one entity</em></strong></li><li>In Monolith, Components are run as a <strong><em>single OS process.</em></strong></li><li>If we made <strong><em>changes in a single component</em></strong>, it <strong><em>requires the deployment of the whole application</em></strong></li><li>If any <strong><em>component requires more Memory, CPU </em></strong>based on the requirement, we need to do <strong><em>vertical scaling for all the replicas</em></strong></li><li>we need to do Horizontal Scaling to Scale (To maintain the Multiple Copies)</li><li><strong><em>Any component</em></strong> of the Monolith application is <strong><em>not scalable</em></strong>, <strong><em>the whole application is not scalable.</em></strong></li></ol><h3><strong>Micro Services</strong> <strong>architecture</strong></h3><ol><li>Micro Service is an<strong><em> independent process </em></strong>and communicates with other micro-services through <strong><em>well-defined interfaces called Application Programming Interfaces </em></strong>(API)</li><li>Micro Services communicates <strong><em>through synchronous protocols Such as HTTP. They usually expose REST (Representational State Transfer)</em></strong> or through <strong><em>Asynchronous protocols Such as AMQP(Advanced Message Queuing Protocol)</em></strong></li><li>These protocols are <strong><em>very simple and are independent of programming languages</em></strong>. So <strong><em>Micro-services are having the flexibility to write in different programming languages based on their functionality</em></strong> and they communicate with each other.</li><li>Each Micro-service is a <strong><em>standalone process with a relatively static external API</em></strong></li><li>It’s <strong><em>possible to develop and deploy each micro-service</em></strong> Separately and <strong><em>changes to one of its services do not require redeployment</em></strong> of any other services</li><li>The advantage of microservices is <strong><em>we can scale the components individually</em></strong>.<strong><em> Components that require horizontal scaling can scale horizontally </em></strong>and At the same time, <strong><em>we can scale the components which require only vertical scaling.</em></strong> Monolith does not have the flexibility to scale components individually based on the requirement.</li><li>Microservices are <strong><em>Elastic, Resilient, Composable, Minimal, and Complete</em></strong><br><strong><em>Elastic</em></strong>: <em>A microservice must be able to scale, up or down, independently of other services in the same application.<br></em><strong><em>Resilient</em></strong><em>: A microservice must fail without impacting other services in the same application.<br></em><strong><em>Composable</em></strong><em>: A microservice must offer an interface that is uniform and is designed to support service composition.<br></em><strong><em>Minimal</em></strong><em>: A microservice must only contain highly cohesive(where things belong together) entities</em><br><strong><em>Complete</em></strong>: <em>A microservice must be functionally complete</em></li></ol><h3>constraints of Microservices</h3><h4>Deployment of Microservices:</h4><ol><li>one of the constraints in microservice is deployment. <strong><em>when the number of components increases deployment-related decisions are increasingly difficult.</em></strong> Not only <strong><em>do the deployment combinations increase but also the number of interdependencies between the components increases</em></strong> by a greater factor.</li><li>Microservices <strong><em>will communicate together as a team</em></strong>, So they need to find and talk to each other. <strong><em>when deploying them someone needs to configure all of them properly to enable them to work as a single system</em></strong>. <strong><em>with increasing microservices this becomes difficult, especially what the Ops team need to do when a server fails.</em></strong></li><li>Microservices are<strong><em> hard to debug and trace the execution calls</em></strong> because they <strong><em>span multiple processes and machines</em></strong>.</li></ol><h4>Understand the divergence of environmental requirements</h4><ol><li>microservices are the <strong><em>independent processes</em></strong> that are <strong><em>developed, deployed and updated individually by the individual teams</em></strong>. So there is a <strong><em>chance of maintaining the same library with different versions in different microservices based on their usage and requirement</em></strong>.it will <strong><em>become a nightmare for the ops team</em></strong> who deploys and manages them on production servers.</li><li>The <strong><em>bigger the number of components you need to deploy</em></strong> on the <strong><em>same host</em></strong>, the <strong><em>harder it will be to manage all their dependencies </em></strong>to satisfy all the requirements</li></ol><h4>Need to provide a consistent environment to applications</h4><ol><li>one of the biggest problems for the developers and ops team is the <strong><em>difference in environments</em></strong>. Not only t<strong><em>he difference between the developer environment and the production environment</em></strong> but also <strong><em>there is a difference even exists between the individual production machines</em></strong>.</li><li>Another unavoidable fact is that the <strong><em>environment of a single production machine will change over time</em></strong>. Production systems can run applications from multiple development teams, So <strong><em>they must provide the proper environment to all applications it hosts, even though they may require different conflicting versions of libraries.</em></strong></li><li>To reduce the number of problems<strong><em> it would be ideal if applications could run the exact same environment during development and in production. So that they have the exact same operating system, libraries, System configuration, network environment and everything else</em></strong>.</li><li>if possible <strong><em>we want the ability to add applications to the same server without affecting any existing applications to that server</em></strong>.</li></ol><h4>Need continuous delivery(Need to Adopt Devops And NoOps strategy)</h4><ol><li>In the last few years, we have also seen a shift in the whole application development process and how applications take care in production. I<strong><em>n the past, the development team job was to create the application and hand it off to the operations team </em></strong>who then deployed and keep it running.</li><li>But now organizations realize that <strong><em>it is better to have the same team that develops the application and also take part in deploying it and needs to take care of it whole lifetime</em></strong>.</li><li>So that <strong><em>Developer, QA and Operations need to collaborate, this practice is called DevOps</em></strong>.</li><li><strong>Benefit:<em> </em></strong><em>Developers have a better understanding of the user needs and they understand the issues and also the problems faced by the Operations team while maintaining the app. It helps in the further development of the app.</em></li><li>To release new versions of applications more often, you need to streamline the deployment process. <strong><em>Ideally, we want developers to deploy the application themselves without the requirement of the ops people</em></strong>.</li><li>But for deploying the application.<strong><em> it requires an understanding of the underline infrastructure and the organization hardware data centre</em></strong>.</li><li>Even though developers, OpsTeam, System administrators working towards achieving the same goal i.e running the software application successfully, <strong><em>Their individual goals are different</em></strong>.</li><li><strong>Developers</strong>: <em>They love creating </em><strong><em>new features</em></strong><em> and improving the user experience.</em><br><strong>System Administrators</strong>: <em>They make sure the underlying Operating System is up to date with all security patches and like that </em><br><strong>Ops Team</strong>: <em>They take care of production deployments and hardware infrastructure they run on. They care about System Security and utilization and other aspects</em>.</li><li>Developers don’t care about these activities and similarly, the Ops team don&#39;t care about the implicit interdependencies of all the application components and They don’t care about How the Operating system and infrastructure affect the application&#39;s behaviour.</li><li>Ideally, we want developers to <strong><em>deploy the application without having knowledge of the hardware and infrastructure without any help from the ops team. This practice is called NoOps.</em></strong> But Someone needs to take care of it.</li></ol><blockquote>To Handle all these mentioned constraints we are making deployment of microservices with Kubernetes. it achieves all of this abstracting actual hardware and infrastructure and exposing a single platform for deploying and running the applications. it helps Developers to deploy and configure the applications without any help of the Ops team and system administrators</blockquote><blockquote>it helps the system administrators to focus on keeping the underlying infrastructure up and running. while not having to know about what actual application is running</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f16fd8beffbc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/art-of-coding/micro-services-and-its-constraints-f16fd8beffbc">Micro Services and its Constraints</a> was originally published in <a href="https://medium.com/art-of-coding">art of coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java 9 — Additional Features (Part-2)]]></title>
            <link>https://medium.com/art-of-coding/java-9-additional-features-part-2-67ca08d2371e?source=rss----ed8b09a8a1de---4</link>
            <guid isPermaLink="false">https://medium.com/p/67ca08d2371e</guid>
            <category><![CDATA[java9]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Chinmay Venkata Sabbam]]></dc:creator>
            <pubDate>Sat, 12 Sep 2020 12:08:09 GMT</pubDate>
            <atom:updated>2020-09-12T12:08:09.152Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java 9 — Additional Features (Part-2)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*3Fj93luaHoZ4E4P31h1Fxw.jpeg" /></figure><p><strong>you need to know about the improvements in java 9</strong> :</p><p><a href="https://medium.com/art-of-coding/java-9-features-part-1-8e847a2edc37">Java 9 Features (Part -1)</a></p><p>In this article we will Focus on the <strong>additional features of Java 9</strong></p><h3><strong>Additional Features in Java 9:</strong></h3><h4>1. Optional (ifPresentOrElse() , stream(),or())</h4><p><strong><em>Before discuss</em></strong> about the Additional Features in Optional. <strong><em>First we will try to understand the Optional</em></strong></p><pre>List&lt;Integer&gt; numbers = Arrays.asList(1,2,3,4,5,6,7,8,9,10);<br>  <strong>//Statement-1</strong>    <br>      numbers.stream()<br>             .<strong>filter(e-&gt; e&gt; 5)</strong><br>             .findFirst(); <strong>// 6 <br>-----------------------------------------------------------------<br> //Statement-2 <br>      </strong>numbers.stream()<br>             .<strong>filter(e-&gt; e&gt; 50)</strong><br>             .findFirst();<strong>// Null</strong></pre><p>Let’s Imagine <strong><em>if there is No Optional parameter in Java</em></strong> , observe the above code block. <strong><em>if we print the statement-1 it will give the output 6</em></strong></p><p><strong><em>if we print the statement-2</em></strong> ,<strong><em> it will give Null or Null Pointer Exception</em></strong>. Generally Null is called smell, especially in functional style of coding . So <strong><em>Effectively in Java, we will return empty List</em></strong>. <strong>But if we need to return the single element then ????</strong></p><blockquote>So<strong> In Java 8, Optional parameter is used in functional style of coding to avoid Null pointer Exceptions.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vxs2Ox-0WhOfJYlhKtdZ5Q.png" /><figcaption>Optional parameter example</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*k4gxcXPAKkWCKSUY5TTRFg.png" /><figcaption>output of the above program</figcaption></figure><p>if we observe the above program. we did not get the Null Pointer Exceptions. Now Question is <br><strong><em>How can we get the parameter from the Optional ???</em></strong></p><p>Let us understand the <strong><em>existed approaches before Java 9</em></strong>. so that we can easily <strong><em>understand the painful point and additional feature in Optional</em></strong></p><blockquote><strong>Note: Don’t try the below program at home or at work place because Optional is the type which is always used at return type but not as Method variable</strong></blockquote><pre><strong>public</strong> <strong>static</strong> <strong>void</strong> process(java.util.Optional&lt;Integer&gt; result) {</pre><pre>// <strong>APPROACH -1 </strong></pre><pre>        result.<strong>get()</strong>; <br>//<em> </em><strong><em>dont do this...... get() is to forget because it blows without telling you NoSuchElement Exception</em></strong> </pre><pre>// <strong>APPROACH -2</strong> </pre><pre>    result.<strong>orElseThrow</strong>(); <br>// <strong><em>it clearly tells you the intension</em></strong></pre><pre>// <strong>APPROACH - 3 </strong></pre><pre>   result.<strong>orElse(0)</strong>; <br>// <strong>gives value or return 0<br></strong> <br>// <strong>APPROACH</strong> <strong>-4</strong>       <br>  result.<strong>ifPresent</strong>(value -&gt; System.out.println(value));<br>        <br>    }<br><strong>public</strong> <strong>static</strong> <strong>void</strong> main(String[] args) {<br>     List&lt;Integer&gt; numbers = Arrays.asList(1,2,3,4,5,6,7,8,9,10);<br>     <br>      java.util.Optional&lt;Integer&gt; op1 = numbers.stream()<br>      .filter(e-&gt; e&gt; 5)<br>      .findFirst();<br>      <br>      java.util.Optional&lt;Integer&gt; op2 = numbers.stream()<br>              .filter(e-&gt; e&gt; 50)<br>              .findFirst();<br>       <strong>process</strong>(op1);<br>       <strong>process</strong>(op2);</pre><pre>}</pre><p><strong><em>Approach-1</em></strong> | result.<strong>get() : <em>Don’t use this method because it blows up with NoSuchElement Exception without any notice</em></strong>, if Optional is empty.</p><p><strong><em>Approach-2</em></strong> | result.<strong>orElseThrow</strong>() : <strong><em>it will throw the Exception with intimation </em></strong>, if Optional is empty. it is better than get() method</p><p><strong><em>Approach-3</em></strong> | result.<strong>orElse(value)</strong>: <strong><em>it will return the value specified</em></strong>, if Optional is empty</p><p><strong><em>Approach-4 </em></strong>| result.<strong>ifPresent((logic)) :<em> it will handle the logic , if Optional is not empty</em></strong></p><blockquote><strong>Problem : if we need to handle some logic , if Optional is empty . then ……………</strong></blockquote><pre><strong>if(!result.isPresent())</strong> {<br>            <br>}</pre><p>if we handle in the above code mentioned, <strong><em>it will comes under the imperative style of coding and not comes under the functional style of coding</em></strong></p><blockquote><strong>So In Java 9, they introduced the ifPresentOrElse() method</strong></blockquote><h4>1.1 ifPresentOrElse():</h4><pre>result.<strong>ifPresentOrElse</strong>(value -&gt; System.out.println(value), ()-&gt; System.out.println(&quot;there is no value&quot;));</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*blBmbDGdK6Oznnhvj5HSAA.png" /><figcaption>ifPresentOrElse Method in java 9</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*VU-f4lAa_nLkP-ejJxZGSw.png" /><figcaption>output of the above program</figcaption></figure><p>Let us Observe the <strong><em>differences between the Optional and the Stream</em></strong></p><p><strong>Optional</strong> may have <strong>0 or 1</strong> values . <strong>Stream</strong> may have <strong>0,1 or more</strong> values that means Optional is a subset of Stream. Now the Question arrived<br><strong>why can’t we use Optional as a Stream ????</strong></p><blockquote><strong>So In Java 9, they introduced the stream() method</strong></blockquote><h4><strong>1.2 stream():</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MFoaBuYSvg6THiEa4o4V4A.png" /><figcaption>stream() method in java 9</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*ynBZRNI6N5J69NWhGSjnmg.png" /><figcaption>output of the above code</figcaption></figure><p><strong>Note</strong> : <em>Stream can iterate not only with empty but also with one or more elements</em></p><h4><strong>1.3 or()</strong>:</h4><p>let us <strong>compare</strong> <strong>or()</strong> with <strong>orElse()</strong> method so that you can clearly understood the difference</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jBL3YBbVlKMfnuJKtI7Qww.png" /><figcaption>Difference between the or and orElse</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v8ovg123eMZ96BbNI9-trw.png" /><figcaption>Comparison Program of or() and orElse() methods</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*1Ie6eraJVlnCgRdHtVJ6hw.png" /><figcaption>output of the above program</figcaption></figure><h4>2. Completable Future (completeOnTimeOut(),orTimeOut(),copy())</h4><p>In Programming we must be careful <strong><em>not only with deadlocks but also with live-locks as well</em></strong> especially when you deal with the <strong><em>Asynchronous Programming.</em></strong></p><blockquote><strong>Completable future consists an asynchronous programming flavor Just like Promises in JavaScript</strong></blockquote><p><strong>live lock</strong> : <br><strong>Pseudo code</strong>:</p><pre><strong>public</strong> <strong>static</strong> <strong>int</strong> factory() {<br>  <strong>try</strong> {<br>  <strong> // if this logic would take 3 hrs time to execute</strong><br>  } <strong>catch</strong> (InterruptedException e) {<br>   e.printStackTrace();<br>  }<br>  <strong>return</strong> 42;<br> }<br> <br>  <strong>CompletableFuture</strong>.supplyAsync(factory())<br>  .thenAccept(System.out::println);</pre><p>if we execute this Completable Future, <strong><em>it takes 3hrs to complete</em></strong>. <strong><em>it is called live lock</em></strong>. especially in <strong>asynchronous programming it could not work</strong>. <strong><em>we need specific amount of timeouts</em></strong>. <strong><em>To Solve this problem, In Java 9 two timeout Methods are introduced in Completable future </em></strong>(<em>completeOnTimeOut</em>() and <em>orTimeOut</em>())</p><h4>2.1 <em>completeOnTimeOut():</em></h4><blockquote>completeOnTimeout(<strong>value</strong>, <strong>time</strong>, <strong>TimeUnit</strong>)</blockquote><p>eg. ::: completeOnTimeout(-1, 2, TimeUnit.SECONDS)</p><p><strong><em>if task will complete with in 2 seconds, it would give the result, if it exceeds 2 seconds it returns value -1</em></strong></p><h4>2.2 orTimeOut():</h4><blockquote>orTimeout(<strong>time</strong>, <strong>TimeUnit</strong>)</blockquote><p>eg ::: orTimeout(2, TimeUnit.SECONDS)</p><p><strong><em>if task will complete with in 2 seconds , it would give the result, if it exceeds timeout the operation</em></strong></p><p>In addition to this Java 9 introduces the <strong>copy()</strong> method. <strong><em>which is used to copy the entire functional Composition of the completable future </em></strong>without creating the new one again</p><h4>2.3 copy():</h4><blockquote>copy(<strong>Completable Future</strong>)</blockquote><pre>CompletableFuture&lt;Integer&gt; cp = CompletableFuture.supplyAsync(CompletableFutureWithJava9::factory);<br> <strong>CompletableFuture&lt;Integer&gt; cp2 = cp.copy();</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EdV9Q4QS5BY9-xoaiviAzQ.png" /><figcaption>CompleteOnTimeOut,orTimeOut,Copy methods in Completable Futures with Java 9</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*7iJUfPjdx_nNABHZRrJQcQ.png" /><figcaption>Output of the above Program</figcaption></figure><p><strong>3. Collectors (Filtering and FlatMapping)</strong></p><p>we all know <strong>that filter() and flatMap() are the functions which are available in the streams. In Java9</strong>, <strong><em>they also introduced in the collectors </em></strong>Interface <strong><em>to solve the different use cases with the functional programming</em></strong></p><p><strong><em>USECASE</em></strong>:</p><pre>LIST 1 ::: {1, 2, 3, 4, 5, 6}, LIST 2 ::: {7, 8, 9, 10}<br>I need output Map&lt;Integer,List&gt; = Map&lt;Size of the List,LIST of even Numbers in List&gt; = {{6,{2,4,6}},{4,{8,10}}</pre><p><strong>it can be easily solve with flatMapping() in collectors</strong> which is introduced in Java 9</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qnKpIEyWr8Q-PhredpNs1A.png" /><figcaption>Solution for above use case is in advanced benefits</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*D1xzsmcQXLsDeCw3sC60Iw.png" /><figcaption>Output of the above Program</figcaption></figure><h4>4. Immutable Collections (of())</h4><p>Before Discussing <strong>about the of() method,</strong> first we need to understand about the <strong>Arrays.asList(elements) </strong>method</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4prUMtqPwbJiV6dSoxMUfA.png" /><figcaption>Arrays.asList Behaviour observation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*GtVPZFfnLzzix2X0qJHASA.png" /><figcaption>output of the above program</figcaption></figure><p>By Seeing this above Program, Do you felt <strong>Arrays.asList(elements) is a immutable ??????</strong></p><p>Lets observe below program</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x83T5ARZG8UAVfPzWLq6VQ.png" /><figcaption>Arrays.aslist (behaviour)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*5XwaetKi_11GNE67PgGV_g.png" /><figcaption>output of the above program</figcaption></figure><p>if you observe the output , <strong>it clear shows that it mutates the value (1 with 4) and it’s class is ArrayList</strong></p><h4>of()</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pwaFbGQA432B9ZiwR7gPxA.png" /><figcaption>Observe the Behaviour of()</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*pfyPK2Tehsu0BZGOBCQpTg.png" /><figcaption>Output of the above program</figcaption></figure><p><strong>Same program if you run with of()</strong>, we are getting the <strong>Exception …. why ???</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ViLcsLjQy84seEqbPOXqkg.png" /><figcaption>Comparision of Arrays.asList() and List.of()</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*VxcZNQ7T-iI2uQ10ChUnqQ.png" /><figcaption>Output of the above program</figcaption></figure><p>Here we can clearly see the difference:</p><blockquote><strong>Arrays.asList()</strong> is <strong><em>mutable</em></strong> and it is having <strong>class name ArrayList</strong> and <strong>List.of()</strong> is <strong>immutable</strong> and it is having a<strong> class Name Immutable Collections</strong></blockquote><pre><strong>Set</strong>&lt;String&gt; set = <strong>Set.of</strong>(&quot;Tom&quot;,&quot;Jerry&quot;,&quot;Hello&quot;);<br><strong>Map</strong>&lt;String,Integer&gt; map = <strong>Map.of</strong>(&quot;a&quot;,1,&quot;b&quot;,2,&quot;c&quot;,3,&quot;z&quot;,5);</pre><blockquote>In the similar way <strong><em>we have Set.of() and Map.of ()</em></strong> which gives you <strong><em>Immutable Collections</em></strong></blockquote><pre>Set&lt;String&gt; set = Set.of(&quot;<strong>Tom</strong>&quot;,&quot;Jerry&quot;,&quot;<strong>Tom</strong>&quot;);</pre><blockquote><strong>Note</strong>: Above code <strong>gives you a RunTimeException</strong>, where as <strong>HashSet will allow</strong></blockquote><pre><strong>RUNTIME EXCEPTIONS:</strong><br>System.out.println(Map.of(&quot;a&quot;,1,&quot;b&quot;,2,&quot;c&quot;,3,<strong>5,&quot;z&quot;</strong>));<br>System.out.println(Set.of(&quot;Tom&quot;,&quot;Jerry&quot;,<strong>123</strong>));<br>System.out.println(Map.of(&quot;a&quot;,1,&quot;<strong>b</strong>&quot;));</pre><pre><strong>COMPILE TIME EXCEPTIONS</strong> :<br>Map&lt;<strong>String,Integer</strong>&gt; map = Map.of(&quot;a&quot;,1,&quot;b&quot;,2,&quot;c&quot;,3,<strong>5,&quot;z&quot;</strong>);<br>Set&lt;<strong>String</strong>&gt; set = Set.of(&quot;Tom&quot;,&quot;Jerry&quot;,<strong>123</strong>);<br>System.out.println(Set&lt;<strong>String</strong>&gt;.of(&quot;Tom&quot;,&quot;Jerry&quot;,<strong>123</strong>));     System.out.println(Map&lt;<strong>String,Integer</strong>&gt;.of(&quot;a&quot;,1,&quot;b&quot;,2,&quot;c&quot;,3,<strong>5,&quot;z&quot;</strong>));</pre><h4>5. Diamond Operator&lt;&gt; Extension for the anonymous classess</h4><p>In Java 1.7, Diamond Operator &lt;&gt; is applicable only for classess. <strong><em>Now it is Extended to the Anonymous classess</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2cuZdK_sOY8uQ0AreB81wg.png" /><figcaption>Diamond Operator for the anonymous classes</figcaption></figure><p>In the above code <strong><em>commented code is in Java 8</em></strong> Implementation.</p><h4>6. Http/2</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kPY_BKudtJ-jnzXvh6rmYw.png" /><figcaption>http2 implementation</figcaption></figure><p>In the Upcoming Blog (Part-3) we will concentrate on<strong> advanced features of Java 9</strong></p><ul><li>JShell</li><li>Modularization (it changes the entire landscape of Java)</li><li>StackWalker(Processing the stacks traces in to Streams)</li></ul><h3>Stay Tuned…….</h3><h3>Follow this Publication for timely updates</h3><h3>Medium :</h3><p><a href="https://medium.com/art-of-coding">https://medium.com/art-of-coding</a></p><h3>Linked in :</h3><p><a href="https://www.linkedin.com/company/art-of-coding/">https://www.linkedin.com/company/art-of-coding/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67ca08d2371e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/art-of-coding/java-9-additional-features-part-2-67ca08d2371e">Java 9 — Additional Features (Part-2)</a> was originally published in <a href="https://medium.com/art-of-coding">art of coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java 9 Features (Part -1)]]></title>
            <link>https://medium.com/art-of-coding/java-9-features-part-1-8e847a2edc37?source=rss----ed8b09a8a1de---4</link>
            <guid isPermaLink="false">https://medium.com/p/8e847a2edc37</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java9]]></category>
            <dc:creator><![CDATA[Chinmay Venkata Sabbam]]></dc:creator>
            <pubDate>Sun, 30 Aug 2020 11:10:52 GMT</pubDate>
            <atom:updated>2020-09-12T12:16:46.239Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*3Fj93luaHoZ4E4P31h1Fxw.jpeg" /></figure><h4>Evaluation of Java:</h4><ol><li>In java 1.7, <strong><em>things are very slow as compared to other JDK languages</em></strong> like Scala, Kotlin. when <strong><em>Java 8</em></strong> releases, it <strong><em>changes the entire landscape of Java</em></strong> because functional programming introduced with Lambdas, Stream API, and Completable Future.</li><li>Till now <strong><em>Java 9 is the biggest release</em></strong> even-though Java 8 changes the entire landscape, because <strong><em>it changed the complete ecosystem of the Java </em></strong>and we can build and deploy the applications with it.</li><li><strong>Release cycle of the JAVA: </strong>The Release cycle of the java changes from JAVA 9,<strong><em> the oracle is releasing the JAVA every 6 months</em></strong>. it doesn’t mean JAVA is developing every 6 months. Features are taking years to develop with out compromise in testing and quality, <strong><em>what ever the features they would complete at that release point of time, they will release that features Instead of waiting for other features to complete</em></strong>.</li></ol><h3>Java 9 Features:</h3><p>I categorized Java 9 Features into 3 categories</p><ol><li>Improvements</li><li>Additional Features</li><li>Advanced Features</li></ol><p><strong><em>In this blog we will Focus on Improvements , Remaining will be published in next part.</em></strong></p><h3>Improvements:</h3><h4>1. Private Methods In Interfaces:</h4><ol><li>Until <strong>Java 7</strong>, Interface is the <strong><em>body of the bundle of Unimplemented methods.</em></strong></li><li><strong><em>In Java 8 , Default and static methods are implemented in Interfaces</em></strong> just like classes. Generally in classes, <strong><em>what ever the common code</em></strong> we have used in the methods <strong><em>can be written as private methods.</em></strong></li><li><strong>If we need to use the common code in these static and Default methods in Interface, where we need to write that common code ???</strong><br>Java 9 provided the solution <strong><em>with the improvement of private methods in interfaces</em></strong>, it provides two types of private methods <br>1. normal <strong><em>private</em></strong> methods<br>2. <strong><em>private static</em></strong> methods</li></ol><blockquote><strong>private static methods are used in the static methods and normal private methods are used in default methods of Interface</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ift1HjLo2xJs7rfbqS5w-g.png" /><figcaption>private methods in interfaces</figcaption></figure><blockquote><strong>NOTE: </strong>I recommend you to not use this feature more in the real time because your interface is blotted with full of code which is not good for understand.</blockquote><h4>2. Try with Resources:</h4><ol><li>when the Java was introduced, At that point of time the most trending language is C++. <strong><em>The painful point in C++ is garbage collection</em></strong>.</li><li>The advantage and disadvantage of the JAVA is the garbage collection because we don’t know at what time it was invoked.</li><li>Generally, Programming requires of <strong><em>two types of garbage collection</em></strong> <br>(a) Memory in <strong><em>the Runtime </em></strong><br>(b) <strong><em>External</em></strong> Resources (Files, Database and socket connections etc).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UMSqTFgd_gTdXCF9y3oh8A.png" /><figcaption>code before java 1.7 to close external resources</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*ILJEx2IB_78EYNQrkK08RQ.png" /><figcaption>output for above code</figcaption></figure><p>if we observe the above code, <strong><em>finalize method is not invoked</em></strong>. Here Managing memory in runtime and Managing external resources both are two different things (which are conflict each other) but Oracle developers thought they will solve these conflict things with the single solution which doesn’t work in the long run.<br>There is anthor method in JDK which is not usable at all i.e is<strong><em> System.gc()<br>Don’t use this because there is no use in it.</em></strong></p><p><strong><em>Good News is In JAVA 9, finalize() method is deprecated</em></strong></p><blockquote>In life and also in programming we solve the problems is to create the new problems</blockquote><blockquote><strong>Here they solved the Garbage collection for memory in runtime. but they created the problem for external resources.</strong></blockquote><blockquote><strong>Java 1.7</strong> provides the solution with <strong>try- with- resources</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zf8xjACK6iJiApNPiY8xqg.png" /><figcaption>JDk 1.7 to close external Resources</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*n_-96XfnmvBX3BcIwskUVQ.png" /><figcaption>Output for above code</figcaption></figure><pre><strong>try</strong>(Resource res = <strong>new</strong> Resource())</pre><blockquote><strong>In 1.7 , They solved the problem with external Resources but it leads to create a anthor problem. we observed the code block, we are making Resource Object is tightly coupled(Bad coding practice).</strong></blockquote><p>Due to this tight coupling , it is very difficult to automate the testcases with Mock or Stub</p><blockquote><strong>In Java 9 , they solved the problem</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6lOANS2RTVArA42TaEMYRQ.png" /><figcaption>code with Java 9 to close external Resources</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*n_-96XfnmvBX3BcIwskUVQ.png" /><figcaption>Output of the above code</figcaption></figure><blockquote><strong>In Java9, they solved the External Resource tightly coupling problem. <br>Now caller can send Resource Object or any extension class of the Resource Object or Resource Mock Object. but it will leads to anthor problem.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*pChVP1011a3XLrVs81S10A.png" /><figcaption>still resource object is accessible even it is closed</figcaption></figure><ol><li>Before Java 9, <strong><em>Resource Object is not accessible out side the try block</em></strong>, But In Java 9 , <strong><em>Resource Object is still accessible for some time even it is closed</em></strong>. we must be take care while writing the code</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*dQ7KrF4m4Po1Xv5ytHRz1w.png" /><figcaption>object used in try block is not mutable</figcaption></figure><p>2. Object used in the try block is <strong><em>final or effectively final</em></strong> and<strong><em> it is not allowed to mutate it .</em></strong></p><h4>3. Usage of _ as variable name is completely removed in Java 9</h4><ol><li>_ is having <strong><em>lot of importance in different programming languages</em></strong> like scala,kotlin etc</li><li>In Java 8, <strong><em>usage of _ as variable showed as warning</em></strong> and In Java 9,<strong><em> they completely removed it .</em></strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*zg2XwVml2bhgiDcYylZqCw.png" /><figcaption>_ removed in java 9</figcaption></figure><h4>4. Take while and Drop while In Streams</h4><p>we all know that In Java 8 , Streams API completely changes the landscape of the Java.<strong><em> Before Discuss about the Java9 improvement, let’s understand the existing methods in Java 8</em></strong>, after that we will clearly understand the improvement in Java 9.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B74ByPrbrRVRha3FQwagKA.png" /><figcaption>Java 8 Stream functionalities</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*X690QBEte7UAYkDOrOz-jw.png" /><figcaption>Output of the above program</figcaption></figure><p><strong>Observations from the above program</strong> :</p><ol><li><strong>filter</strong> takes a <strong><em>Predicate</em></strong> .<strong><em> It is like a gate, that opens or closes per element</em></strong></li><li><strong>limit</strong> takes a <strong><em>integer</em></strong>. <strong><em>it is like a door, that is open. but once it is closed then it may closes for ever</em></strong></li><li><strong>skip</strong> takes a <strong><em>integer</em></strong>. <strong><em>it is also like a door, that is closed. but once it is opened that it may opened forever</em></strong>.(opposite to limit).</li></ol><p>observe the<strong><em> limit and skip functions</em></strong> , it takes <strong><em>integer</em></strong> as input.</p><p><strong>lets think about below use cases</strong>. <br><strong>Use Case: 1</strong></p><pre>List&lt;Integer&gt; numbers = Arrays.asList(11,12,13,14,51,16,17,81,91)<br><strong>I need to limit this  list until number &lt; 50 </strong></pre><p>Now we need to <strong><em>limit</em></strong> the list<strong><em> based on the condition</em></strong> , not on the number. <strong>How we will solve this use case in Java 8 ???</strong><br><strong>solution with imperative style of coding is simple:</strong></p><pre><strong>for</strong>(int number : numbers){<br>   if(number &gt; 50)<br>        <strong>break</strong>;<br><strong>System</strong>.out.<strong>println</strong>(number);<br>}</pre><p><strong>How can you solve this use case with FUNCTIONAL PROGRAMMING </strong>In Java 8 ???? — it’s not possible in Java 8</p><p>To Solve this use case<strong> take-While(Predicate)</strong> Comes in to the picture<strong> in Java 9</strong></p><pre>numbers.stream()<br>         .<strong>takeWhile(e -&gt; e&lt;50)</strong><br>         .forEach(System.out::println);</pre><p><strong>Use Case:2</strong></p><pre>List&lt;Integer&gt; numbers = Arrays.asList(11,12,13,14,51,16,17,81,91)<br><strong>I need to skip this  list until number &lt; 50</strong></pre><p>Now we need to <strong><em>Skip</em></strong> the list <strong><em>based on the condition</em></strong> , not on the number. <strong>How we will solve this use case in Java 8 ???</strong><br><strong>solution with imperative style of coding is simple:</strong></p><pre><strong>boolean </strong>isAllowed<strong> = false;<br>for</strong>(int number : numbers){<br>   if(number &lt; 50 &amp;&amp; !isAllowed) {<br>        continue;<br>   }<br>  isAllowed = true;<br><strong>System</strong>.out.<strong>println</strong>(number);<br>}</pre><p><strong>How can you solve this use case with FUNCTIONAL PROGRAMMING </strong>In Java 8 ???? — it’s not possible in Java 8</p><p>To Solve this use case<strong> drop-While(Predicate)</strong> Comes in to the picture<strong> in Java 9</strong></p><pre>numbers.stream()<br>         .<strong>dropWhile</strong>(e -&gt; e&lt;50)<br>         .forEach(System.out::println);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bt6Ygp5IGRLBuQgETh2iEg.png" /><figcaption>implementation of takewhile and dropwhile</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*ubArUnUWMe4iHKJDVYMduQ.png" /><figcaption>output of the above code</figcaption></figure><blockquote><strong>NOTE: break(imperative) = takeWhile(functional)</strong></blockquote><p><strong>Haskell vs Java Naming convention</strong></p><pre>   <strong>Haskell ----------------------- JAVA</strong><br>   take(number) ------------------ limit(int)<br>   drop(number) ------------------ skip(int)<br>   takeWhile(Predicate) ---------- takeWhile(Predicate)<br>   dropWhile(Predicate) --------   dropWhile(Predicate)</pre><h4>5. iterate method in streams</h4><p>Before we discuss about the iterate method, Just Imagine <strong><em>you and your friend</em></strong> start debate between <strong><em>imperative</em></strong> and <strong><em>functional</em></strong> style implementations. <strong><em>you are supporting functional style of coding</em></strong> . Let us see <strong><em>Both of you giving counter implementations in imperative and functional style in Java 8</em></strong> .</p><p><strong>Imperative style :</strong></p><pre><strong>for</strong>(<strong>int</strong> i=0; i&lt;5; i++) {<br>      <br> }</pre><p><strong>Functional style</strong> :</p><pre>IntStream.<strong>range</strong>(0,5)<br>        .forEach(System.out::println);</pre><p><strong>Imperative style :</strong></p><pre><strong>for</strong>(<strong>int</strong> i=0; i&lt;=5; i++) {<br>             <br>}</pre><p><strong>Functional Style :</strong></p><pre>IntStream.<strong>rangeClosed</strong>(0,5)<br>        .forEach(System.out::println);</pre><p><strong>Imperative</strong></p><pre><strong>for</strong>(int i=0; i&lt;=5; i= i+2) {<br>            <br>}</pre><p><strong>Functional style</strong> in Java 8 ???? — you lost the debate</p><ol><li>To Solve the above use case <strong><em>iterate</em></strong> method <strong><em>comes in to the picture in Java 9</em></strong></li><li>Most Commonly used interfaces in Functional style of Coding is Predicate,Supplier, Consumer and Function <br>Let’s See iterate method is how intuitive it is</li></ol><pre><strong>for</strong>(int i=0; i&lt;=5; i= i+2) {<br>            <br>}<br>for(<strong>seed</strong>,<strong>predicate</strong>,<strong>function</strong>) {<br>}<br>//Java 9:<br>IntStream.<strong>iterate(seed,predicate,function)</strong></pre><p><strong>Imperative and functional style implementations in JAVA 9</strong></p><pre><strong>// imperative <br>for</strong>(int i=0; i&lt;=5; i= i+2) {<br>            <br>}</pre><pre><strong>// functional</strong></pre><pre>IntStream.<strong>iterate</strong>(0,i-&gt; i&lt;=5, i-&gt; i+2)<br>        .forEach(System.out::println);</pre><p><strong>Infinite Loop Implementation In Imperative and functional style implementations in Java 9</strong></p><pre><strong>// imperative <br>for</strong>(int i=0; <strong>;</strong> i= i+2) {<br>            <br>}</pre><pre><strong>// functional</strong></pre><pre>IntStream.<strong>iterate</strong>(0,i-&gt; i+2)<br>        .forEach(System.out::println);</pre><blockquote><strong>Note : In iterate method Predicate is optional Parameter , if you did not mention Predicate , it becomes an infinite loop</strong></blockquote><p>In the Blog (Part-2) we concentrated on<strong> additional features of Java 9 in</strong></p><p><a href="https://medium.com/art-of-coding/java-9-additional-features-part-2-67ca08d2371e">Java 9 — Additional Features (Part-2)</a></p><p>In the Upcoming Blog (Part-3) we will concentrate on<strong> advanced features of Java 9</strong></p><ul><li>JShell</li><li>Modularization (it changes the entire landscape of Java)</li><li>Stack Walker API</li></ul><h3>Stay Tuned…….</h3><h4>Follow this Publication for timely updates</h4><h4>Medium :</h4><p><a href="https://medium.com/art-of-coding">https://medium.com/art-of-coding</a></p><h4><strong>Linked in :</strong></h4><p><a href="https://www.linkedin.com/company/art-of-coding/">https://www.linkedin.com/company/art-of-coding/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e847a2edc37" width="1" height="1" alt=""><hr><p><a href="https://medium.com/art-of-coding/java-9-features-part-1-8e847a2edc37">Java 9 Features (Part -1)</a> was originally published in <a href="https://medium.com/art-of-coding">art of coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Buzz words in Multi-threading …..]]></title>
            <link>https://medium.com/art-of-coding/buzz-words-in-multi-threading-7c363f35a90a?source=rss----ed8b09a8a1de---4</link>
            <guid isPermaLink="false">https://medium.com/p/7c363f35a90a</guid>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[executorservice]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Chinmay Venkata Sabbam]]></dc:creator>
            <pubDate>Tue, 31 Dec 2019 01:58:44 GMT</pubDate>
            <atom:updated>2019-12-31T02:11:39.157Z</atom:updated>
            <content:encoded><![CDATA[<h3>Buzz words in Multi-threading …..</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/0*eTHyWmR6-VLUueQJ.png" /></figure><p>In Multi-threading we usually confused between the <br>Volatile,Synchronized and Atomic</p><p>To clearly understand these words , you need to understand two scenarios which we facing in highly concurrent environments .</p><ol><li>visibility problem</li><li>synchronization problem</li></ol><h3>1. visibility problem</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*GCeBOLW0L9ZKswKI5nVHEg.png" /><figcaption>visibility problem occur in highly concurrent environments</figcaption></figure><p>Lets consider above scenario which causes an visibility problem between two threads in highly concurrent environments.</p><p>we have global variable status = true, while thread-1 starts some processing when the status = true</p><p>After some time when the thread-2 starts,status is updated with false then thread-1 is also stops processing. this is what usually we expected to be happen <strong><em>but In some highly concurrent environments it is not possible</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*pkIFGYd71Gkx0RSeePjoww.png" /><figcaption>In highly concurrent environments this is the scenario</figcaption></figure><blockquote><strong>if two threads works on two different cores, then status what you have updated by thread-2 in above scenario is does not reflect to the thread-1 because it is stored in local cache. This is called visibility problem between the two threads</strong></blockquote><p>To solve the above problem we need to use volatile keyword</p><pre>public <strong>volatile</strong> boolean status = true ;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*tbxbHSaeOpMDvINb5om1Jg.png" /><figcaption>this is How volatile would works</figcaption></figure><blockquote>if you mention the volatile to the specific variable, <strong>what ever the modifications you will made by the every thread is written to the shared cache.</strong></blockquote><h3>2. synchronization problem</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*1b41iIuwTOlCffM4rgVSHw.png" /><figcaption>synchronization problem in highly concurrent environments</figcaption></figure><p>In this scenario, it looks like single operation , it is not single operation</p><p>read →modify →write</p><p>we have the int value = 1 . when thread-1 runs starts running first then i=2 and later thread-2 runs then i = 3 .</p><p>In vice-versa if thread-2 starts first then also i=2 and later thread-1 then i=3.</p><p>But in highly concurrent environments , some times it does not work correctly</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*rxT3bnxHdggYhymR_-H1Yg.png" /><figcaption>How it works some times in a wrong manner</figcaption></figure><h4>if JVM schedules the thread which is interdependent on each other</h4><ol><li>thread 1 →read the value = 1 →committed to shared cache because value is volatile.</li><li>thread 2 → read the value =1 →committed to shared cache because value is volatile</li><li>thread 1 → update the value = 2 →committed to shared cache because value is volatile but <strong><em>thread-2 does not read from shared cache because read operation is already completed</em></strong></li><li>again thread 2 → update the value = 2 committed shared cache which is completely wrong.</li></ol><p>This is synchronization problem ……..</p><p>To avoid the synchronization problem,we use <strong>Atomic variables</strong> or <strong>synchronized blocks for variables</strong>, for methods we use<strong> synchronized</strong> key word.</p><h4>Use Case to understand synchronization problem:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0314fd401c450634c1887af4fe34f10/href">https://medium.com/media/f0314fd401c450634c1887af4fe34f10/href</a></iframe><ol><li>In above program I took ConcurrentHashMap consists <strong><em>Party Name as key and number of votes as a value</em></strong>.</li><li>I took <strong><em>5 threads</em></strong> and <strong><em>Each thread vote 1000 votes to each party</em></strong> , i.e means as per our expectation, after running all the threads <strong><em>each party must and should contains 5000 votes</em></strong></li><li>But <strong><em>I run these 5 threads in Multi-threading Environment</em></strong>, Due to this<strong><em> I got an different output</em></strong> as shown as below</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/0*xVmjDba1b0tMnAnx.png" /><figcaption>Different parties get different votes other than 5000</figcaption></figure><h4>we need to use atomic variables to solve the above problem <br>solution :</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78f63534ac9e17b88ccc22f708c19451/href">https://medium.com/media/78f63534ac9e17b88ccc22f708c19451/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/0*kWssFw9vFgbCyytc.png" /><figcaption>output as we expected</figcaption></figure><h4>Difference between the volatile and atomic</h4><ol><li>volatile is suitable only for <strong><em>read →write</em></strong> cases</li><li>atomic variables are used for <strong><em>read →update →write</em></strong> cases</li></ol><h3>3. Use Case to avoid visibility and synchronization problem with singleton Implementation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7P4KUxB9-PFjhbSjtKIjlQ.png" /><figcaption>perfect Singleton Implementation in java</figcaption></figure><ol><li>In high concurrent environment there is a possibility that two threads will enter</li></ol><p>2. JIT compiler rearrange the byte code in a way that <strong><em>reference to the getInstance() set before the constructor has finished it’s execution</em></strong>.this means there is a chance that,method getInstance() returns the object <em>which is not completely initialized.</em></p><blockquote><strong>Java 5 . for instance variables, the variables which are marked as volatile are only visible to the other threads when the constructor of the object initialized completely</strong></blockquote><h3>Conclusion ……</h3><p>when we are using global variables in multi-threaded environments , to avoid visibility and synchronization problems we need to use in below mentioned way</p><ol><li>volatile →flags</li><li>Atomic Variables →counters</li><li>Atomic References → Cache</li><li>synchronization block with volatile →variable is global and Need visibility to every thread what is the current state of the object.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c363f35a90a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/art-of-coding/buzz-words-in-multi-threading-7c363f35a90a">Buzz words in Multi-threading …..</a> was originally published in <a href="https://medium.com/art-of-coding">art of coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Callable and Runnable….. & Need of Completable Future(part-3)]]></title>
            <link>https://medium.com/art-of-coding/callable-and-runnable-need-of-completable-future-part-3-2e31732cb6e4?source=rss----ed8b09a8a1de---4</link>
            <guid isPermaLink="false">https://medium.com/p/2e31732cb6e4</guid>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[threadpoolexecutor]]></category>
            <dc:creator><![CDATA[Chinmay Venkata Sabbam]]></dc:creator>
            <pubDate>Tue, 10 Dec 2019 18:14:35 GMT</pubDate>
            <atom:updated>2019-12-10T18:14:35.463Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/598/0*uUCjtZxp8VBo2V7y.png" /></figure><p>Before Reading this blog please go through for better understanding</p><p><a href="https://medium.com/art-of-coding/deeper-insights-of-thread-pool-need-of-asynchronous-programming-in-java-part-2-cf47995a50a5">Deeper insights of Thread-pool &amp; Need of Asynchronous programming in Java ….(part-2)</a></p><h3>Why Callable …..?</h3><p>In previous blogs…. In all examples tasks execute through thread-pool does not return any results, that means all examples implemented with the Runnable interface. if tasks execute through thread pool has some outcome, then ….. we need to implement through callable interface.</p><p>Runnable interface is a functional interface, which implements the run method. run() method is a void method. <strong><em>execute() method of the Executor Thread-pool took Runnable interface as parameter</em></strong>.</p><p>Callable is also a functional interface as similar as the Runnable interface. which implements call() method. it has a return type. it is not an void method.<strong><em> submit() method of the ExecutorThread-pool took Callable interface as parameter. it will give results as Future</em></strong></p><blockquote>submit() method accepts both Runnable and callable as parameters. but it returns Future when we send callable interface as a parameter.</blockquote><h3>Future</h3><p>Future is a Object which creates at the time of the task executing, when each task is completed, result is stored in the Future Object. if you use the method <strong>future.get() <em>then it is wait until the task get completed and then it will give result.</em></strong></p><p>we can understand callable and future through below example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1WpiWq7SI3elvdc_d3r69Q.png" /><figcaption>Example with callable and Future</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*m6rC3M37ejP_BF4l28wncA.png" /><figcaption>Callable and Future execution in fixed thread pool</figcaption></figure><ol><li>In above example Each task implements the callable interface and it returns the String. there are 10 tasks and 3 threads executes these 10 tasks asynchronously with the Fixed thread Pool Executor.</li><li>when the task-1 executes then there is no string in Future Object. if task executed completely then only string is stored in Future Object.</li><li>when we perform a get() operation on the Future Object of a particular task,<strong><em> main thread is blocked </em></strong>and <strong><em>it will wait until the task is completed even though if task is not completed at that time and it gives result while we iterating all Future Objects of these 10 tasks.</em></strong></li></ol><blockquote>Note : <strong>Try not to use Future.get()</strong> method in real Time, if task took more time, main thread will block and it may lead to dead-lock condition.<strong>Always use with get() method with specific time period</strong></blockquote><pre>future.get(long, TimeUnit);</pre><h3>Advantage of Callable</h3><pre>List&lt;Future&lt;?&gt;&gt; futures = executorPool.<strong>invokeAll</strong>(List&lt;class extends Callable&gt;);<br>Future future = executorPool.<strong>invokeAny</strong>(class extends Callable);</pre><p>This invokeAll() and invokeAny() could have an added advantage to callable then Runnable.</p><blockquote><strong>use-case : if you have more number of tasks if you send all the tasks to the Non-blocking queue, it may lead to memory issues in real time.</strong></blockquote><p><em>if you took all rows from the big data like Cassandra and we need to perform the tasks on executor thread pool directly. it will lead to memory issues in real time.At </em><strong><em>that time invokeall() method saves us from the memory issues</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c4zFYse4LSkx6RsZ-tK99Q.png" /><figcaption>Real time advantages with callable interface</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OvJNXL1-zw9EsaEwsead-w.png" /><figcaption>output image of the above program</figcaption></figure><p>if you observe the above program, it consists of 95 tasks and thread pool of 3 threads. here we are insisting only 10 tasks will submitted to the thread pool at a time. it executes in this manner</p><p>1–10 tasks — — — — 10 tasks submitted — — — — — — — — — 3 threads</p><p>10–20 tasks — — — —10 tasks submitted — — — — — — — — 3 threads</p><p>20–30 tasks — — — — 10 tasks submitted — — — — — — — — 3 threads</p><p>30–40 tasks — — — — 10 tasks submitted — — — — — — — — 3 threads</p><p>40–50 tasks — — — — 10 tasks submitted — — — — — — — — 3 threads</p><p>50–60 tasks — — — — 10 tasks submitted — — — — — — — — 3 threads</p><p>60–70 tasks — — — — 10 tasks submitted — — — — — — — — 3 threads</p><p>70–80 tasks — — — — 10 tasks submitted — — — — — — — — 3 threads</p><p>80–90 tasks — — 10 tasks submitted(seen in output picture) — 3 threads</p><p>90–95 tasks — — — — 5 tasks submitted — — — — — — — — 3 threads</p><h3>Comparison Between Runnable and callable interfaces</h3><h4>Runnable</h4><ol><li>it is a interface with single method . <strong><em>so we can apply a lambda expressions</em></strong></li><li>it <strong><em>can be implemented through both execute() and submit()</em></strong> methods of the executor thread pool.</li><li>it <strong><em>can be implemented in a Thread constructor</em></strong></li></ol><pre>Thread th = new Thread(Runnable runnable);</pre><p>4. it <strong><em>does not have support for invokeAll() and invokeAny() </em></strong>methods of the executor thread Pool</p><p>5. it <strong><em>does not return any output and it does not throw any checked exceptions</em></strong> (exceptions which are handled during compile time)</p><p>6. Runnable interface is introduced in Java <strong><em>from JDK 1.0</em></strong></p><h4><strong>Callable</strong></h4><ol><li>it is a interface with single method . <strong><em>so we can apply a lambda expressions</em></strong></li><li>it <strong><em>can be implemented through only submit() method of the executor thread pool.</em></strong></li><li>it<strong><em> cannot be implemented in a Thread constructor</em></strong></li></ol><p>4. it <strong><em>have support for invokeAll() and invokeAny() methods </em></strong>of the executor thread Pool</p><p>5. it <strong><em>will return output through Future Object which acts like holder and it throws checked exceptions </em></strong>(exceptions which are handled during compile time)</p><p>6. Callable interface is introduced in Java from <strong><em>JDK 1.5</em></strong></p><h3>Is Java does Really Supports an Asynchronous Programming ?</h3><p><strong>No until java 1.7</strong> , when Java 8 supports an Asynchronous programming when it is flexible for functional style of programming by Implementing <strong><em>Completable Future which is similar semantics as Promises in Java Script</em></strong>.</p><h4><strong>In what case completable Future Required</strong>……….</h4><p>lets focus on below program</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NbZPZLvUPzRAqyFdDi0yyw.png" /><figcaption>multiple methods in executor thread pool</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*XzL0dc9J1qt76X0Gf6im6g.png" /><figcaption>Output of the above program</figcaption></figure><p><em>In the above program two methods getting an order and paying an order will independent of each-other and it executed asynchronously without any blocking of the main thread</em>.</p><h3>Need of Completable Future:</h3><p>Let us consider we have three methods, which are <strong><em>dependent</em></strong> on each other</p><ol><li>orderBooking (CPU intensive)</li><li>orderConformation (IO intensive)</li><li>payment conformation (CPU intensive)</li></ol><blockquote>you need to execute all these methods as dependent for each client ,but client to client as an Independent flow as shown as below diagram without dependent of main thread.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*sq8lR4seb1ZhtuPH5IMucw.png" /><figcaption>Need to execute in this way</figcaption></figure><p><strong>Program Generally we write ….</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2o8E1vhNnagcNEKmZgmz2w.png" /><figcaption>Multiple methods with dependency example</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*wsxbzYLMO2Cx1CyJe3XkfQ.png" /><figcaption>way of running above program</figcaption></figure><p>Above program runs for 100 clients</p><p>Initially it runs <strong><em>orderBooking</em></strong> for 100 clients</p><p>then it runs <strong><em>orderConformation</em></strong> for 100 clients</p><p>then it runs <strong><em>paymentConformation</em></strong> for 100 clients</p><blockquote><strong>which is equal to sequential execution and it is completely in correct. to solve this use case completable futures are used. we will discuss in further posts</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e31732cb6e4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/art-of-coding/callable-and-runnable-need-of-completable-future-part-3-2e31732cb6e4">Callable and Runnable….. &amp; Need of Completable Future(part-3)</a> was originally published in <a href="https://medium.com/art-of-coding">art of coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deeper insights of Thread-pool & Need of Asynchronous programming in Java ….(part-2)]]></title>
            <link>https://medium.com/art-of-coding/deeper-insights-of-thread-pool-need-of-asynchronous-programming-in-java-part-2-cf47995a50a5?source=rss----ed8b09a8a1de---4</link>
            <guid isPermaLink="false">https://medium.com/p/cf47995a50a5</guid>
            <category><![CDATA[threadpoolexecutor]]></category>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[thread-pool]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Chinmay Venkata Sabbam]]></dc:creator>
            <pubDate>Tue, 26 Nov 2019 10:57:40 GMT</pubDate>
            <atom:updated>2019-11-26T10:57:40.499Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deeper insights of Thread-pool &amp; Need of Asynchronous programming in Java ….(part-2)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*dwVE9Yrt9Utj3LSLQodHCQ.png" /></figure><p>Before reading this blog for the better understanding please go through</p><p><a href="https://medium.com/art-of-coding/deeper-insights-of-thread-pool-need-of-asynchronous-programming-in-java-part-1-d22741da1648">Deeper insights of Thread-pool &amp; Need of Asynchronous programming  in Java ….(part-1)</a></p><h3>Types of Executor Thread Pools</h3><h3>1. Fixed Thread-pool</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*mH5xZ62m4E5KUKv75KkqXw.png" /><figcaption>Fixed Thread pool</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*9lXNhuO4Ie0Ww3ybkebl2w.png" /><figcaption>Thread structure for the fixed thread pool</figcaption></figure><p><strong><em>Working :</em></strong></p><ol><li>As per the above code snippet we are running <strong>100</strong> tasks asynchronously . using <strong>5 </strong>threads</li><li>Fixed thread pool creates <strong>5</strong> threads and it uses <strong><em>Blocking Unbounded queue</em></strong> which stores <strong>100 </strong>tasks.</li><li>Initially<strong> 5</strong> threads picked <strong>5</strong> tasks from blocking queue and <strong><em>execute them parallel</em></strong>. As soon as the task completed by one thread, it pick’s up the anthor task from the blocking queue.<strong><em> In this way 5 threads executes 100 tasks Asynchronously</em></strong>.</li></ol><h3>2.Cached Thread-pool</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*Xroq9ZRGaAp6PyppIQsGfQ.png" /><figcaption>Cached Thread Pool</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*ak9JE1SCO_s08yUMf6qJXg.png" /><figcaption>Thread Structure for the Cached Thread Pool</figcaption></figure><p><strong><em>Working :</em></strong></p><ol><li>In Cached pool there is no fixed number of threads and It consists of <strong><em>synchronous queue</em></strong> which hold <strong>1</strong> task</li></ol><p>2. if there are <strong>100</strong> tasks, if <strong>10</strong> threads are busy when<strong><em> 11 th</em></strong> tasks is submitted 11 th thread is created i.e means <strong><em>t1 to t100</em></strong> threads are created .</p><blockquote><strong>if Thread is idle for 60 seconds then thread pool can kill the tasks i.e means slowly thread pool starts shrinking</strong></blockquote><h3>3.Synchronized Thread Pool</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NFgOmsgAqcm-c2QMrVG8mA.png" /><figcaption>synchronized thread pool</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*WLKhXf0zkwbxqkxlk1MmIg.png" /><figcaption>Thread Structure for the Scheduled Thread Pool</figcaption></figure><p><strong><em>Working:</em></strong></p><ol><li>It is the thread pool which is used to schedule the tasks at the Time delay</li></ol><p>Eg : security checks or login checks</p><p>2. Tasks are placed in the Delay Queue.It does not mean that tasks are running in the sequential order, it executes in parallel</p><p>3. If two tasks t1 and t2 and you will schedule the t1 task after 20 minutes and t2 task after 5 minutes then t2 task is executes first and then t1 executes</p><p>4. (1) <strong>schedule ()</strong> →Task after a certain delay</p><pre>ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);</pre><pre>  scheduledExecutorService.schedule(()-&gt;  System.out.println(Thread.currentThread().getName()+&quot;Task to Run After 10 Seconds Delay&quot;),10,TimeUnit.SECONDS);</pre><blockquote>In the above code, Task will run after <strong>10</strong> seconds . this task will execute only one time</blockquote><p>(2) <strong>scheduleAtFixedRate()</strong> →tasks which are run at every specific interval of time</p><pre>ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);<br>scheduledExecutorService.scheduleAtFixedRate(()-&gt;  System.out.println(Thread.currentThread().getName()+&quot;Task to run repeatedly after every 10 seconds after 70 seconds delay&quot;), 70, 10, TimeUnit.SECONDS);</pre><blockquote>In the above code, Task will execute repeatedly after every 10 seconds after 75 seconds delay</blockquote><p>(3)<strong> scheduleAtFixedDelay()</strong> →task which run after the certain interval based on the previous task completes</p><pre>ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);<br>scheduledExecutorService.scheduleWithFixedDelay(()-&gt;  System.out.println(Thread.currentThread().getName()+&quot;Task to run repeatedly after every 10 seconds after previous tasks completes after 100 seconds delay&quot;), 80, 10, TimeUnit.SECONDS);</pre><blockquote>In the above code, Task will execute after every 10 seconds when the previous tasks completes,after 80 seconds delay</blockquote><p>5. Scheduled Thread Pool can create any number of Threads, if it is required</p><h3>4. Single Threaded Executor</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DPMw08SlBkV2KcaRVyg5lA.png" /><figcaption>Single Thread pool executor</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*PgY0ysFXyEQzWFrok6acFg.png" /><figcaption>Thread structure for Single Threaded Executor</figcaption></figure><p><strong><em>Working:</em></strong></p><ol><li>Single Threaded Executor consists of only one thread.</li></ol><p>2. If thread is killed due to the Exception, The pool creates the anthor thread and tasks are executed which are present in the blocking queue . these threads executes sequentially.</p><h3>Internal Implementation of the Executor Thread Pool</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jsfamrC-LuTSS8XyWsmwtQ.png" /><figcaption>Internal Implementation of the Executor Thread Pool</figcaption></figure><p><strong>Parameters Description :</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8941c61f67619527e92cd425136b912/href">https://medium.com/media/b8941c61f67619527e92cd425136b912/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*ogtSn66dRbXob2jCbiMvrQ.png" /><figcaption>Thread pool sizes</figcaption></figure><p>Core pool size = initial size</p><p>Current pool size = threads added/deleted based on pool type and keep a live time</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34e4c7d3fdc41cec958bf5710113cd5c/href">https://medium.com/media/34e4c7d3fdc41cec958bf5710113cd5c/href</a></iframe><p><strong>Note:</strong> core pool threads are never killed unless <strong><em>allowCoreThreadTimeOut(boolean value)</em></strong> is set to be true</p><h3>Types of Queues used in Different Thread Pools</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/388553aceabf575ddbda3d7985adceab/href">https://medium.com/media/388553aceabf575ddbda3d7985adceab/href</a></iframe><h3>Rejection Handler</h3><p>if you design a custom Thread Pool. There is a chances that tasks are rejected by the Thread Pool, because it is implemented by using the Array Blocking Queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*odyzL6j0K311hPIQw0GzwA.png" /><figcaption>Tasks rejects by the thread pool</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4jInGa1_ri5YUHkJgG80Ng.png" /><figcaption>Output of the above program</figcaption></figure><p>In the above program , <strong><em>size of the Array Blocking queue is 300 </em></strong>and <strong><em>Number of tasks submitting to the thread Pool is 500</em></strong>. initial size is 10 and maximum pool size is 100.</p><p>when threads are busy in running the first <strong>100 </strong>tasks , <strong>remaining 300 tasks are present in queue</strong>. when we are submitting the<strong> 401</strong> th task to the queue. there is no place to store the tasks. so it throws an Rejection Handler Exception.</p><h3>Handling Rejection Handler Exceptions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h1vwe_9HJlLFR5FrooN7Xg.png" /><figcaption>Handling Custom Rejection Handlers</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wjiJoTMwPUVvw7ZiNmp1ww.png" /><figcaption>Output of the above program</figcaption></figure><p>we can handle the <strong><em>RejectedExecutionExceptions</em></strong> by creating the <strong>Custom Rejection Handler </strong>as shown as above code</p><p><strong><em>Custom Rejection Handler with lambda Expressions</em></strong></p><pre>(runnable,executor) -&gt; System.out.println(&quot;I am Handling CustomRejection Handler&quot;)</pre><p><strong><em>Custom Rejection Handler with Boiler plate code</em></strong></p><pre><br>     private static class CustomRejection Handler implements RejectedExecutionHandler {<br>     <br>     @Override <br>     public void rejectedExecution(Runnable r, ThreadPoolExecutor executor){<br>      // perform any operations<br>     }</pre><h3>Life Cycle of the Executor Thread Pool</h3><ol><li><strong>executor.shutdown() :</strong></li></ol><p>It initiates the shutdown process , <strong><em>but it does not accept other tasks after calling this</em></strong> , but <strong><em>it can complete all the tasks</em></strong> which are present in blocking queue</p><blockquote>If we submit the task after calling this , we can face a Rejection Execution Exception</blockquote><p><strong>2. executor.isshutdown()</strong> :</p><p>to <strong><em>check</em></strong> <strong><em>shutdown()</em></strong> is initiated or not</p><p><strong>3. executor.isTerminated():</strong></p><p>it will <strong><em>return true if all tasks are completed including queued ones</em></strong></p><p><strong>4. executor.awaitTermination(10,TimeUnit.Seconds)</strong></p><p><strong><em>block until </em></strong>all tasks are completed or until the timeout occurs</p><p><strong>5</strong>. <strong>List&lt;Runnable&gt; runnables = executor.shutdownNow()</strong></p><p>it will stop all the tasks abruptly . but <strong><em>it returns all the tasks which are queued in blocking queue</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*00V2599VMKQMyXAIfgzf1Q.png" /><figcaption>Life cycle of a thread Pool Executor</figcaption></figure><blockquote>In the Next Part we will discuss about the Future and what use-case Future could not solve and improvements of the Java 8 in Asynchronous Programming and how we can implement the Custom Blocking pool without facing memory issues etc… stay tuned …..</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf47995a50a5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/art-of-coding/deeper-insights-of-thread-pool-need-of-asynchronous-programming-in-java-part-2-cf47995a50a5">Deeper insights of Thread-pool &amp; Need of Asynchronous programming in Java ….(part-2)</a> was originally published in <a href="https://medium.com/art-of-coding">art of coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>