<?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 anil gola on Medium]]></title>
        <description><![CDATA[Stories by anil gola on Medium]]></description>
        <link>https://medium.com/@anil.java.story?source=rss-98afcb09928f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*65c58B3kHFqt_LHihT8u3w.jpeg</url>
            <title>Stories by anil gola on Medium</title>
            <link>https://medium.com/@anil.java.story?source=rss-98afcb09928f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 18:32:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anil.java.story/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[Why Spring Constructor Injection is the recommended approach?]]></title>
            <link>https://medium.com/@anil.java.story/why-spring-constructor-injection-is-the-recommended-approach-75edca1f9b36?source=rss-98afcb09928f------2</link>
            <guid isPermaLink="false">https://medium.com/p/75edca1f9b36</guid>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[recommended-approach]]></category>
            <category><![CDATA[constructor-injection]]></category>
            <category><![CDATA[springboot-3]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[anil gola]]></dc:creator>
            <pubDate>Wed, 03 Jan 2024 05:52:16 GMT</pubDate>
            <atom:updated>2024-12-04T10:20:56.356Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a question that I have seen candidates struggle to answer. A few months ago, I too used to struggle to answer. For the whole of my life, I used to use field injection. First of all, let us see various types of dependency injection in Spring framework.</p><h3>1. Constructor Injection — the recommended approach</h3><p>Let us see the code for Constructor Injection</p><pre>@RestController<br>public class TestController {<br>    private TestRepository testRepository;<br>    <br>    @Autowired<br>    public TestController(TestRepository testRepository) {<br>        this.testRepository = testRepository;<br>    }<br>}<br><br>@Repository<br>class TestRepository{<br><br>}</pre><p>We have a TestRepository that is injected into the <strong>TestController</strong>. We have declared <strong>TestRepository</strong> as <strong>private</strong> and initialised it in our controller. Now that Spring is smart enough, if we have only one constructor, there is no need to declare <strong><em>@</em>Autowired</strong> over the Controller Constructor. It will detect and inject the necessary dependency.</p><p>Now our code looks like this:</p><pre>@RestController<br>public class TestController {<br>    private TestRepository testRepository;<br><br>    public TestController(TestRepository testRepository) {<br>        this.testRepository = testRepository;<br>    }<br>}<br><br>@Repository<br>class TestRepository{<br><br>}</pre><p>We can go one step further; since we do not want our repository to be changed once initialised, we can make our testRepository as final. This making <strong>testRepository</strong> <strong>final</strong> is what really makes it the recommended approach. Now, the code looks like this:</p><pre>@RestController<br>public class TestController {<br>    private final TestRepository testRepository;<br><br>    public TestController(TestRepository testRepository) {<br>        this.testRepository = testRepository;<br>    }<br>}<br><br>@Repository<br>class TestRepository{<br><br>}</pre><p>Can we go one step further and make this code even better? It turns out that if we can use <strong>lombok</strong>, then this will look even sweeter. <strong>@RequiredArgsContructor</strong> helps us to write very crisply and clearly.</p><pre>@RestController<br>@RequiredArgsConstructor<br>public class TestController {<br>    private final TestRepository testRepository;<br><br>}<br><br>@Repository<br>class TestRepository{<br><br>}</pre><p>A question can be asked: what if we have more than seven dependents? Why 7? Because Sonar may start to complain. But if that is the case, then probably we have to start thinking about the design of our application. Too much dependency on one component is, of course, not right. But with Lombok, we are covered, and Sonar will not complain.</p><h3>2. Setter Injection</h3><p>With setter injection, our code looks like below:</p><pre>@RestController<br>public class TestController {<br>    private  TestRepository testRepository;<br><br>    @Autowired<br>    public void setTestRepository(TestRepository testRepository) {<br>        this.testRepository = testRepository;<br>    }<br>}<br><br>@Repository<br>class TestRepository{<br><br>}</pre><p>There is now some inherent problems with the above code. Since we are using Setter to autowire our dependency, somebody may change the behaviour of testRepository to what Spring is providing us. Locking horns with spring-managed beans is not on. Since we are using setters, making testRepository final will make our compiler angry. Also, setter injection was never used, right from the early days of the spring framework.</p><h3>3. Field Injection</h3><p>Let us see the code for Field Injection</p><pre><br>@RestController<br>public class TestController {<br>    @Autowired<br>    private  TestRepository testRepository;<br>}<br><br>@Repository<br>class TestRepository{<br><br>}</pre><p>This is the code we all have been used to, who have been using Spring for a decade. It looks nice and clear. I too loved it, but there are some issues with it. First, <strong>this is somehow violating the very nature of Java</strong>. We are declaring <strong>testRepository</strong> as <strong>private</strong>, and yet we are allowing Spring to inject the dependency into it. <strong>In Java, if a field is private in a class, we do not allow its access from outside of the class</strong>. But spring is able to do with <strong>reflection APIs</strong>, even though legally possible, but not in the spirit of Java. Java developers don’t like to mess with <strong>reflection APIs.</strong></p><p>Also, since this dependency injection can only take place after the TestController is initialised, there may be a chance that our testRepository will be <strong>null </strong>by the time we start using it. Chances are very low, but on some bad days, this may occur in production.</p><p>I hope you get the gist. If this question pops up in an interview, you should be ready to answer it in a nice and concise manner.</p><p>Also, if you are interested in SQL, please watch my playlist on youtube: <a href="https://www.youtube.com/playlist?list=PL40GtTTY6_-loL5nQ5Qe4cV_I3-9wwYVG">https://www.youtube.com/playlist?list=PL40GtTTY6_-loL5nQ5Qe4cV_I3-9wwYVG</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75edca1f9b36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#4 Asynchronous Programming in Java-Launching Several Tasks with CompletionStage APIs]]></title>
            <link>https://medium.com/@anil.java.story/4-asynchronous-programming-in-java-launching-several-tasks-with-completionstage-apis-8da909e6266e?source=rss-98afcb09928f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8da909e6266e</guid>
            <category><![CDATA[completablefuture]]></category>
            <category><![CDATA[multithreading-in-java]]></category>
            <category><![CDATA[future]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[anil gola]]></dc:creator>
            <pubDate>Sat, 24 Jun 2023 09:27:53 GMT</pubDate>
            <atom:updated>2023-06-24T09:28:44.837Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog is in continuation of the previous blog.</p><blockquote><a href="https://medium.com/@anil.java.story/approach-to-non-blocking-code-part-3-78cb1671db49">https://medium.com/@anil.java.story/approach-to-non-blocking-code-part-3-78cb1671db49</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XVslAEqNaNSfktnzBZLmng.png" /></figure><p>Here we will see how we can launch several tasks with the help of CompletionStage APIs.</p><p>Let’s consider our tasks now.</p><pre> Supplier&lt;Quotation&gt; fetchQuotationA = () -&gt; {<br>            try {<br>                Thread.sleep(RandomUtils.nextInt(450,500));<br>            } catch (InterruptedException e) {<br>                throw new RuntimeException(e);<br>            }<br>            return new Quotation(RandomUtils.nextInt(1,100),&quot;server-A&quot;);<br>        };<br><br>  Supplier&lt;Quotation&gt; fetchQuotationB = () -&gt; {<br>      try {<br>          Thread.sleep(RandomUtils.nextInt(450,500));<br>      } catch (InterruptedException e) {<br>          throw new RuntimeException(e);<br>      }<br>      return new Quotation(RandomUtils.nextInt(1,100),&quot;server-B&quot;);<br>  };<br><br>  Supplier&lt;Quotation&gt; fetchQuotationC = () -&gt; {<br>      try {<br>          Thread.sleep(RandomUtils.nextInt(450,500));<br>      } catch (InterruptedException e) {<br>          throw new RuntimeException(e);<br>      }<br>      return new Quotation(RandomUtils.nextInt(1,100),&quot;server-C&quot;);<br>  };<br><br>  Supplier&lt;Quotation&gt; fetchQuotationD = () -&gt; {<br>      try {<br>          Thread.sleep(RandomUtils.nextInt(450,500));<br>      } catch (InterruptedException e) {<br>          throw new RuntimeException(e);<br>      }<br>      return new Quotation(RandomUtils.nextInt(1,100),&quot;server-D&quot;);<br>  };<br><br>  Supplier&lt;Quotation&gt; fetchQuotationE = () -&gt; {<br>      try {<br>          Thread.sleep(RandomUtils.nextInt(450,500));<br>      } catch (InterruptedException e) {<br>          throw new RuntimeException(e);<br>      }<br>      return new Quotation(RandomUtils.nextInt(1,100),&quot;server-E&quot;);<br>  };</pre><p>Instead of <strong>Callables</strong>, we now have <strong>Suppliers</strong>. <strong>Suppliers</strong> are just like <strong>Callables</strong>; it’s just that the <strong>Supplier</strong> doesn’t declare any exceptions. No checked exception is thrown by the <strong>Supplier</strong>, which is not the case with <strong>Callables</strong>. And, by the way, this is better.</p><p>As in my previous blogs, we will collect these suppliers in an <strong>ArrayList</strong>, just like below.</p><pre>var taskList = List.of(fetchQuotationA,<br>        fetchQuotationB,<br>        fetchQuotationC,<br>        fetchQuotationD,<br>        fetchQuotationE );</pre><p>Now, we can submit all these Suppliers to our <strong>CompletableFutures</strong> as we did in ExecutorService, just like below.</p><pre>var futures = new ArrayList&lt;CompletableFuture&lt;Quotation&gt;&gt;();<br>for(Supplier&lt;Quotation&gt; task : taskList){<br>  var future =   CompletableFuture.supplyAsync(task); <br>  futures.add(future);<br>}</pre><p><strong>CompletableFuture.supplyAsync </strong>immediately returns a <strong>CompletableFuture</strong>. It’s the same as <strong>Future</strong>, but with a lot more features. In fact, <strong>CompletableFuture</strong> implements both the <strong>Future</strong> and <strong>CompletionStage</strong> interfaces.</p><p>Now, we need to collect the result of all the futures in an <strong>ArrayList</strong>, something like below.</p><pre>List&lt;Quotation&gt; quotations = new ArrayList&lt;Quotation&gt;();</pre><p>To do that, we need to iterate over the futures array list.</p><pre>List&lt;CompletableFuture&lt;Void&gt;&gt; voids = new ArrayList&lt;&gt;();<br>for(CompletableFuture&lt;Quotation&gt; completableFuture : futures){<br>    CompletableFuture&lt;Void&gt; result =<br>            completableFuture.thenAccept(quotation -&gt; quotations.add(quotation));<br>    voids.add(result);<br>}</pre><p><strong>CompletableFuture</strong> has a method called <strong>thenAccept</strong>, which accepts a <strong>Consumer</strong>. This <strong>Consumer</strong> is executed when the previous task is completed. Of course, both tasks(previous and the Consumer task) are executed asynchronously in other threads. By default, tasks are executed by threads from the <strong>ForkJoin</strong> pool. Also, <strong>thenAccept</strong> returns immediately with a <strong>CompleteFuture</strong>. Since it accepts a <strong>Consumer</strong>, <strong>CompletableFuture</strong> is of type Void.</p><p>Now, we need to do the following to make sure that our main thread doesn’t exit too early. If it exits early, then our tasks, which are running asynchronously in some other threads, will not get a chance to complete, and we will see nothing in our console. j<strong>oin</strong> is similar to <strong>get</strong> method in the future; it’s just that it doesn’t throw any checked exceptions.</p><p>Also, the below line is not part of my application</p><pre>for(CompletableFuture&lt;Void&gt; r : voids){<br>    r.join(); // blocking , but this is not a part of my application<br>}</pre><p>One more thing I need to point out is that since tasks are being executed asynchronously in some other threads, we have race conditions on the below line</p><pre>List&lt;Quotation&gt; quotations = new ArrayList&lt;Quotation&gt;();</pre><p>The above collection is not concurrent-aware. So let’s make the above-line thread safe by using some concurrent-aware collections.</p><pre>Collection&lt;CompletableFuture&lt;Void&gt;&gt; voids = new ConcurrentLinkedDeque&lt;&gt;();</pre><p>Now, we are thread-safe. We have a quotation collection, and now we can find the best quotation, as we did in our previous blogs, with the following code:</p><pre>var bestQuotation =  quotations.stream()<br>         .min(Comparator.comparing(Quotation::getValue))<br>         .orElseThrow();</pre><p>Let’s also wrap this in start and end instants, just like below.</p><pre>var startInstant = Instant.now();<br> var futures = new ArrayList&lt;CompletableFuture&lt;Quotation&gt;&gt;();<br> for(Supplier&lt;Quotation&gt; task : taskList){<br>   var future =   CompletableFuture.supplyAsync(task);<br>   futures.add(future);<br> }<br><br> Collection&lt;Quotation&gt; quotations = new ConcurrentLinkedDeque&lt;&gt;();<br> Collection&lt;CompletableFuture&lt;Void&gt;&gt; voids = new ConcurrentLinkedDeque&lt;&gt;();<br> for(CompletableFuture&lt;Quotation&gt; completableFuture : futures){<br>     var result =<br>             completableFuture.thenAccept(quotation -&gt; quotations.add(quotation));<br>     voids.add(result);<br> }<br><br> for(CompletableFuture&lt;Void&gt; r : voids){<br>     r.join(); // blocking , but this is not a part of my application<br> }<br><br>var bestQuotation =  quotations.stream()<br>         .min(Comparator.comparing(Quotation::getValue))<br>         .orElseThrow();<br><br><br> var endInstant = Instant.now();<br> System.out.println(&quot;Asynchronously - Best Quotation is [&quot;+  bestQuotation.value+&quot;]&quot;<br>         + &quot; Best server is [&quot;+bestQuotation.serverDescription+ &quot;]&quot;<br>         + &quot; (millis) &quot; + Duration.between(endInstant,startInstant).toMillis());</pre><p>Let’s run the programme several times and analyse the results.</p><pre>Asynchronously - Best Quotation is [4] Best server is [server-B] (millis) -508<br><br>Asynchronously - Best Quotation is [8] Best server is [server-C] (millis) -497<br><br>Asynchronously - Best Quotation is [5] Best server is [server-A] (millis) -508<br><br>Asynchronously - Best Quotation is [6] Best server is [server-A] (millis) -487</pre><p>This code is roughly taking the same amount of time as our executor services. At this point, you may wonder what’s the deal with this. The pattern looks exactly the same. Bear with me; we will discuss how we could chain our tasks and create asynchronous pipelines with these Completion Stage APIs in coming blogs. Stay tuned to this space.</p><blockquote><strong>My youtube channel:</strong></blockquote><blockquote><strong>Asynchronous Programming</strong> : <a href="https://www.youtube.com/playlist?list=PL40GtTTY6_-kmdeUznc1XeaTAb3zLlO6K">https://youtu.be/AHL2zuZ_5_k</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8da909e6266e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#3 Asynchronous Programming in Java-Launching Several Tasks Concurrently]]></title>
            <link>https://medium.com/@anil.java.story/approach-to-non-blocking-code-part-3-78cb1671db49?source=rss-98afcb09928f------2</link>
            <guid isPermaLink="false">https://medium.com/p/78cb1671db49</guid>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[synchronous]]></category>
            <category><![CDATA[concurrently]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[anil gola]]></dc:creator>
            <pubDate>Sun, 18 Jun 2023 10:22:31 GMT</pubDate>
            <atom:updated>2023-06-24T09:31:47.511Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog is a continuation of my previous blog:</p><blockquote><a href="https://medium.com/@anil.java.story/approach-to-non-blocking-in-java-part-2-b1699b50e428">https://medium.com/@anil.java.story/concurrent-vs-asynchronous-16a8323c9ccf</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z9fBGcl7MABN-gBQetTZzw.png" /></figure><p>In our previous blog, we launched several tasks synchronously and checked the time it took. In this blog, we will also execute the same callables but concurrently in executor services and check their time. The callables are the same as shown below.</p><pre>Callable&lt;Quotation&gt; fetchQuotationA = () -&gt; {<br>    Thread.sleep(RandomUtils.nextInt(450,500));<br>    return new Quotation(RandomUtils.nextInt(1,100),&quot;server-A&quot;);<br>};<br><br>Callable&lt;Quotation&gt; fetchQuotationB = () -&gt; {<br>    Thread.sleep(RandomUtils.nextInt(450,500));<br>    return new Quotation(RandomUtils.nextInt(1,100),&quot;server-B&quot;);<br>};<br><br>Callable&lt;Quotation&gt; fetchQuotationC = () -&gt; {<br>    Thread.sleep(RandomUtils.nextInt(450,500));<br>    return new Quotation(RandomUtils.nextInt(1,100),&quot;server-C&quot;);<br>};<br><br>Callable&lt;Quotation&gt; fetchQuotationD = () -&gt; {<br>    Thread.sleep(RandomUtils.nextInt(450,500));<br>    return new Quotation(RandomUtils.nextInt(1,100),&quot;server-D&quot;);<br>};<br><br>Callable&lt;Quotation&gt; fetchQuotationE = () -&gt; {<br>    Thread.sleep(RandomUtils.nextInt(450,500));<br>    return new Quotation(RandomUtils.nextInt(1,100),&quot;server-E&quot;);<br>};<br></pre><p>We collected our tasks on a list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*em_7RmMIP2q7NqzS1hVxOw.png" /></figure><p>Now we are going to submit our task to a pool of threads. Let’s create a pool of threads first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QtyRJ7VFkey-VvikGNZ_Lw.png" /></figure><p>Now, it’s time to submit our task to this executor service.</p><pre>var futures = new ArrayList&lt;Future&lt;Quotation&gt;&gt;();<br> for(Callable&lt;Quotation&gt; task : taskList){<br>     futures.add(executorService.submit(task));<br> }</pre><p>Let’s collect the result of all this future now.</p><pre>var quotations = new ArrayList&lt;Quotation&gt;();<br>for(Future&lt;Quotation&gt; future : futures){<br>    quotations.add(future.get()); // blocking call<br>}</pre><p>Now it’s just a classical stream question to find the best quotations.</p><pre>var bestQuotation =  quotations.stream()<br>         .min(Comparator.comparing(Quotation::getValue))<br>         .orElseThrow();</pre><p>Let’s wrap this operation in startInstant and endInstant, and the whole code will look like below:</p><pre> public static void run_concurrenlty() throws ExecutionException, InterruptedException {<br>        Callable&lt;Quotation&gt; fetchQuotationA = () -&gt; {<br>            Thread.sleep(RandomUtils.nextInt(450,500));<br>            return new Quotation(RandomUtils.nextInt(1,100),&quot;server-A&quot;);<br>        };<br><br>        Callable&lt;Quotation&gt; fetchQuotationB = () -&gt; {<br>            Thread.sleep(RandomUtils.nextInt(450,500));<br>            return new Quotation(RandomUtils.nextInt(1,100),&quot;server-B&quot;);<br>        };<br><br>        Callable&lt;Quotation&gt; fetchQuotationC = () -&gt; {<br>            Thread.sleep(RandomUtils.nextInt(450,500));<br>            return new Quotation(RandomUtils.nextInt(1,100),&quot;server-C&quot;);<br>        };<br><br>        Callable&lt;Quotation&gt; fetchQuotationD = () -&gt; {<br>            Thread.sleep(RandomUtils.nextInt(450,500));<br>            return new Quotation(RandomUtils.nextInt(1,100),&quot;server-D&quot;);<br>        };<br><br>        Callable&lt;Quotation&gt; fetchQuotationE = () -&gt; {<br>            Thread.sleep(RandomUtils.nextInt(450,500));<br>            return new Quotation(RandomUtils.nextInt(1,100),&quot;server-E&quot;);<br>        };<br><br>        var taskList = List.of(fetchQuotationA,<br>                fetchQuotationB,<br>                fetchQuotationC,<br>                fetchQuotationD,<br>                fetchQuotationE );<br>        var executorService =  Executors.newFixedThreadPool(6);<br>        var startInstant = Instant.now();<br><br>        var futures = new ArrayList&lt;Future&lt;Quotation&gt;&gt;();<br>        for(Callable&lt;Quotation&gt; task : taskList){<br>            futures.add(executorService.submit(task));<br>        }<br><br>        var quotations = new ArrayList&lt;Quotation&gt;();<br>        for(Future&lt;Quotation&gt; future : futures){<br>            quotations.add(future.get()); // blocking call<br>        }<br><br>       var bestQuotation =  quotations.stream()<br>               .min(Comparator.comparing(Quotation::getValue))<br>               .orElseThrow();<br>       var endInstant = Instant.now();<br>       System.out.println(&quot;Concurrently - Best Quotation is [&quot;+  bestQuotation.value+&quot;]&quot;<br>                + &quot; Best server is [&quot;+bestQuotation.serverDescription+ &quot;]&quot;<br>                + &quot; (millis) &quot; + Duration.between(endInstant,startInstant).toMillis());<br>       executorService.shutdown();<br>    }</pre><p>Now we will run both the synchronous method and the asynchronous method simultaneously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c6W2-ARGjyIcMUUf0Ckb-w.png" /></figure><p>Let’s check the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*95thAzn3CPeFO7J-0pmtYg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7GIdEZrRRKm6xtHXixyk_Q.png" /></figure><p>Clearly, we can see a difference of nearly 5 times less when executing our task concurrently. We have done better here. In the next blog, we will see how we can achieve the same with completion stage APIs in Java.</p><p><strong>Next part:</strong></p><blockquote><a href="https://medium.com/@anil.java.story/4-asynchronous-programming-in-java-launching-several-tasks-with-completionstage-apis-8da909e6266e">https://medium.com/@anil.java.story/4-asynchronous-programming-in-java-launching-several-tasks-with-completionstage-apis-8da909e6266e</a></blockquote><blockquote><strong><em>My youtube channel:</em></strong></blockquote><blockquote><strong><em>Asynchronous Programming</em></strong><em> : </em><a href="https://www.youtube.com/playlist?list=PL40GtTTY6_-kmdeUznc1XeaTAb3zLlO6K"><em>https://youtu.be/AHL2zuZ_5_k</em></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78cb1671db49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Approach to non blocking in Java, part 2]]></title>
            <link>https://medium.com/@anil.java.story/approach-to-non-blocking-in-java-part-2-b1699b50e428?source=rss-98afcb09928f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1699b50e428</guid>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[concurrent-programming]]></category>
            <category><![CDATA[synchronous]]></category>
            <dc:creator><![CDATA[anil gola]]></dc:creator>
            <pubDate>Sun, 18 Jun 2023 07:51:16 GMT</pubDate>
            <atom:updated>2023-06-26T04:52:48.598Z</atom:updated>
            <content:encoded><![CDATA[<h3>#2 Asynchronous Programming in Java-Launching Several Tasks Synchronously</h3><p>This blog is in continuation to my previous blog:</p><blockquote><a href="https://medium.com/@anil.java.story/concurrent-vs-asynchronous-16a8323c9ccf">https://medium.com/@anil.java.story/concurrent-vs-asynchronous-16a8323c9ccf</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FPWON8bqxcn-GOKxcvWHxA.png" /></figure><p>We have precisely defined the definitions of synchronous, asynchronous, and concurrent. We should know that we should avoid blocking calls to make sure that we increase the throughput of our application with the current underlying hardware.</p><p>We need to start somewhere, and what better way to do that than to launch several tasks in a synchronous way and see how much time it takes?</p><p>The example we would be using is quotations. We would hit several quotation servers to fetch the quotation, and our aim is to find the best quotations. We would hit five quotation servers.</p><pre>Callable&lt;Quotation&gt; fetchQuotationA = () -&gt; {<br>    Thread.sleep(RandomUtils.nextInt(450,500));<br>    return new Quotation(RandomUtils.nextInt(1,100),&quot;server-A&quot;);<br>};<br><br>Callable&lt;Quotation&gt; fetchQuotationB = () -&gt; {<br>    Thread.sleep(RandomUtils.nextInt(450,500));<br>    return new Quotation(RandomUtils.nextInt(1,100),&quot;server-B&quot;);<br>};<br><br>Callable&lt;Quotation&gt; fetchQuotationC = () -&gt; {<br>    Thread.sleep(RandomUtils.nextInt(450,500));<br>    return new Quotation(RandomUtils.nextInt(1,100),&quot;server-C&quot;);<br>};<br><br>Callable&lt;Quotation&gt; fetchQuotationD = () -&gt; {<br>    Thread.sleep(RandomUtils.nextInt(450,500));<br>    return new Quotation(RandomUtils.nextInt(1,100),&quot;server-D&quot;);<br>};<br><br>Callable&lt;Quotation&gt; fetchQuotationE = () -&gt; {<br>    Thread.sleep(RandomUtils.nextInt(450,500));<br>    return new Quotation(RandomUtils.nextInt(1,100),&quot;server-E&quot;);<br>};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9c6qKGw5He30t9kQmxHusg.png" /></figure><p>This callable task mimics the HTTP server, where it takes nearly 450 to 500 milliseconds to respond.</p><p>We will be executing all these tasks synchronously and will see how much time it takes. First, we would collect all our tasks on some kind of list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FFkLCkOILAG0aB_KDDJq_w.png" /></figure><p>After that, it would be a simple classical stream question. We open a stream on taskList, execute all tasks in map operation, then find the minimum and open the optional with orElseThrow.</p><pre>  Quotation bestQuotation =  taskList.stream()<br>                .map(SynchronizedTest::executeTask)<br>                .min(Comparator.comparing(it -&gt; it.value)) // Optional<br>                .orElseThrow();</pre><pre> private static Quotation executeTask(Callable&lt;Quotation&gt; task) {<br>        try {<br>            return task.call();<br>        } catch (Exception e) {<br>            throw new RuntimeException(e);<br>        }<br>    }</pre><p>We could wrap this whole stream operations like below to gauge the time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LuGmKnhXw-rsd2UGZUthJg.png" /></figure><p>We would run this programme many times to see our output from the main method.</p><pre> public static void main(String[] args) throws InterruptedException {<br>             run();<br>   }</pre><p>The results are as below after executing the programme four times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_rz-yogAANaCF1eqwdcudA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OhimtoCZR9lms0ionH-09g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RDO7ZfAdyxs8xgH0GkEdaQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*193l97QN7zL6acRiELbXeg.png" /></figure><p>When executing our task synchronously, we are getting the best quotations from different servers, and the time taken is roughly between 2350 ms and 2410 ms.</p><p>We have achieved something here. We need to improve from here.</p><p><strong>Next part:</strong></p><blockquote><a href="https://medium.com/@anil.java.story/approach-to-non-blocking-code-part-3-78cb1671db49">https://medium.com/@anil.java.story/approach-to-non-blocking-code-part-3-78cb1671db49</a></blockquote><blockquote><strong>My youtube channel:</strong></blockquote><blockquote><strong>Asynchronous Programming</strong> : <a href="https://www.youtube.com/playlist?list=PL40GtTTY6_-kmdeUznc1XeaTAb3zLlO6K">https://youtu.be/AHL2zuZ_5_k</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1699b50e428" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#1 Asynchronous Programming in Java-Concurrent vs Asynchronous]]></title>
            <link>https://medium.com/@anil.java.story/concurrent-vs-asynchronous-16a8323c9ccf?source=rss-98afcb09928f------2</link>
            <guid isPermaLink="false">https://medium.com/p/16a8323c9ccf</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[concurrent]]></category>
            <category><![CDATA[asynchronous]]></category>
            <dc:creator><![CDATA[anil gola]]></dc:creator>
            <pubDate>Tue, 06 Jun 2023 06:18:23 GMT</pubDate>
            <atom:updated>2023-06-24T09:38:05.586Z</atom:updated>
            <content:encoded><![CDATA[<p>There are subtle differences between the concurrent and asynchronous programming models, and in this blog, we will precisely define these terms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5LUV0YimNAk7mnoC1fP0tQ.png" /></figure><p>First things first, “<strong>concurrent</strong>” means running your code in several threads so that more things can be done at the same time.</p><p><strong>Synchronous</strong>: The thread that launched the task needs to wait for the task to complete before continuing to work.</p><p><strong>Asynchronous</strong>: The task will be executed at some point in the future, and there is no need to wait for task to complete by <strong>main</strong> thread.</p><pre>ExecutorService executorService =  Executors.newFixedThreadPool(3);<br>Future&lt;String&gt; weatherFuture = executorService.submit(() -&gt; getWeatherFromServerA());<br>Future&lt;Double&gt; quotationFuture = executorService.submit(() -&gt; getQuotationFromServerA());<br><br>weatherFuture.get(); // blocking call , // line no 4<br>quotationFuture.get(); // blocking call // line no 5</pre><p>We have run the above two tasks in different sets of threads; we can say that concurrent execution of code is happening, but suddenly at lines 4 and 5, <strong>we have a blocking call </strong>😮. The main thread submitted the two tasks, which will be executed at some point in the future in separate threads, but the main thread has to wait at line 4. Overall, even though this code looks like it’s fulfilling the criteria of concurrent and asynchronous, it’s actually simple concurrent but synchronous code. There is no way we could write asynchronous code prior to Java 8. Let’s write this as asynchronous code with the help of <strong>CompletableFuture</strong></p><pre>public static void main(String[] args) {<br>   var result = <br>      CompletableFuture.supplyAsync(Weather::getWeatherFromServerA)<br>      .thenAcceptBoth( CompletableFuture.supplyAsync((Quotation::getQuotationFromServerA)),<br>      (weather, quotation) -&gt; System.out.println(weather + &quot;:&quot; + quotation)) ;<br> }</pre><p>The tasks <strong>Weather::getWeatherFromServerA</strong> and <strong>Quotation::getQuotationFromServerA </strong>will be executed at some time in the future. Also, the main thread is not waiting for the result. So the code is fully asynchronous. Do the above codes run concurrently? Yes, as both tasks are running in the <strong>ForkJoin</strong> pool. Hence, it’s both concurrent and asynchronous. In <strong>CompletableFuture</strong>, we can even precisely define in which thread our task should run.</p><p>Now the question is: can a task be asynchronous and yet run on a single thread? <strong>The answer is Yes</strong>. Consider the following code snippet:</p><pre>List.of(&quot;A&quot;,&quot;B&quot;,&quot;C&quot;)<br>        .sort(Comparator.naturalOrder());</pre><p>The task submitted to the <strong>sort</strong> method will be executed at some point in the future, but it will be run by the main thread. We really don’t know how many times the comparator will be called; it really depends on the underline sorting algorithm; if it is merge sort, then it will be called logarithmic of n.</p><p><strong>Clearly, a task can be asynchronous but not concurrent. Also, a programme may be concurrent but not asynchronous, as we have seen with executor services.</strong></p><p><strong>CompletableFuture APIs have been built on top of the concurrent model. With these APIs, we can build concurrent asynchronous APIs.</strong></p><p>I hope you got the gist.</p><p><strong>Next part:</strong></p><blockquote><a href="https://medium.com/@anil.java.story/approach-to-non-blocking-in-java-part-2-b1699b50e428">https://medium.com/@anil.java.story/approach-to-non-blocking-in-java-part-2-b1699b50e428</a></blockquote><blockquote><strong>My youtube channel:</strong></blockquote><blockquote><strong>Asynchronous Programming</strong> : <a href="https://www.youtube.com/playlist?list=PL40GtTTY6_-kmdeUznc1XeaTAb3zLlO6K">https://youtu.be/AHL2zuZ_5_k</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16a8323c9ccf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CompletableFuture: Querying Multiple Servers Asynchronously, fetching the first result]]></title>
            <link>https://medium.com/@anil.java.story/completablefuture-querying-multiple-servers-asynchronously-fetching-the-first-result-24c7217868b7?source=rss-98afcb09928f------2</link>
            <guid isPermaLink="false">https://medium.com/p/24c7217868b7</guid>
            <category><![CDATA[completablefuture]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[java8]]></category>
            <dc:creator><![CDATA[anil gola]]></dc:creator>
            <pubDate>Mon, 05 Jun 2023 12:45:52 GMT</pubDate>
            <atom:updated>2023-06-16T19:16:09.388Z</atom:updated>
            <content:encoded><![CDATA[<p>In one of our projects, we needed to fetch something from the server, and the result was used further in the code. But the problem with the server is that most of the time it does not give the result on the first hit, but on the second or sometimes third hit, we used to get the result, and this was causing errors in our application.</p><p>So, the first solution was simple: we could retry till we got the proper result, and this was ok, but suddenly the latency started to creep in. Then I came up with the following solution:</p><p>We will hit the servers asynchronously several times, wait for the first proper result, and cancel all other requests. This is where <strong>CompletableFuture</strong> come with a very handy method</p><pre>public &lt;U&gt; CompletableFuture&lt;U&gt; applyToEither(<br>    CompletionStage&lt;? extends T&gt; other, Function&lt;? super T, U&gt; fn)</pre><p>This is an instance method and is called on a <strong>CompletableFuture.</strong> When any of the complete futures is finished first, its result is sent to the function.</p><p>Now consider the following code snippets, which mimic the http server.</p><pre>public static String getWeatherFromServerA(){ // returning result in 300 ms<br>          sleep(300);<br>          return &quot;Partly-Sunny&quot; + &quot; server-A&quot;;<br>}<br>public static String getWeatherFromServerB(){ // returning result in 500 ms<br>        sleep(500);<br>        return &quot;Partly-Sunny&quot; + &quot; server-B&quot;;<br>}<br>public static String getWeatherFromServerC(){ // returning result in 100 ms<br>        sleep(100);<br>        return &quot;Partly-Sunny&quot; + &quot; server-C&quot;;<br>}<br><br>public static void sleep(int millis){    // extracted sleep here, and making<br>        try{                             // catch empty to avoid propagation of  <br>            Thread.sleep(millis);        // exception<br>        }<br>        catch (InterruptedException ex){}<br>    }</pre><p>We have three servers that will be queried simultaneously.</p><pre>  CompletableFuture&lt;String&gt; result1  =   <br>            CompletableFuture.supplyAsync(FutureUtils::getWeatherFromServerA);<br>  CompletableFuture&lt;String&gt; result2  =   <br>            CompletableFuture.supplyAsync(FutureUtils::getWeatherFromServerB);<br>  CompletableFuture&lt;String&gt; result3  =   <br>            CompletableFuture.supplyAsync(FutureUtils::getWeatherFromServerC);</pre><p>Now we need to join these with the help of the <strong>applyToEither</strong> function, like below.</p><pre>CompletableFuture finalResult = result1.applyToEither(result2, x -&gt; x)<br>                                       .applyToEither(result3, x -&gt; x);</pre><p>The chaining can be done with n numbers of <strong>CompletableFutures</strong>. The second argument is just an <strong>identity function</strong>. It means that whichever result finishes first (results 1 and 2), the result will be passed to this function. It&#39;s just that it&#39;s an identity function in our case.</p><p>It could be written directly as</p><pre>var result =  CompletableFuture.supplyAsync(FutureUtils::getWeatherFromServerA)<br>    .applyToEither(CompletableFuture.supplyAsync(FutureUtils::getWeatherFromServerB), x -&gt; x)<br>    .applyToEither(CompletableFuture.supplyAsync(FutureUtils::getWeatherFromServerC), x -&gt; x);</pre><p>And since x -&gt; x is an identity function, it can be re-written more precisely as</p><pre>var result =  CompletableFuture.supplyAsync(FutureUtils::getWeatherFromServerA)<br>        .applyToEither(CompletableFuture.supplyAsync(FutureUtils::getWeatherFromServerB), Function.identity())<br>        .applyToEither(CompletableFuture.supplyAsync(FutureUtils::getWeatherFromServerC), Function.identity());</pre><p>And finally, we can call join to wait for the result from any one of the three, just like below.</p><pre>var result =  CompletableFuture.supplyAsync(FutureUtils::getWeatherFromServerA)<br>        .applyToEither(CompletableFuture.supplyAsync(FutureUtils::getWeatherFromServerB), Function.identity())<br>        .applyToEither(CompletableFuture.supplyAsync(FutureUtils::getWeatherFromServerC), Function.identity());<br><br>System.out.println(result.join());</pre><p>Simple and precise. <strong>CompletableFuture</strong> is very powerful for writing asynchronous code, and we will see some amazing patterns in this beautiful Java API in the coming days. Watch this space for more.</p><p><strong>My youtube channel:</strong></p><p><strong>Asynchronous Programming</strong> : <a href="https://www.youtube.com/playlist?list=PL40GtTTY6_-kmdeUznc1XeaTAb3zLlO6K">https://youtu.be/AHL2zuZ_5_k</a></p><p><strong>My talks in English </strong>: <a href="https://youtube.com/playlist?list=PL40GtTTY6_-ksLCcjKcHLALPEq66WHpwO">https://youtube.com/playlist?list=PL40GtTTY6_-ksLCcjKcHLALPEq66WHpwO</a></p><p><strong>My talks in Hindi</strong>: <a href="https://www.youtube.com/playlist?list=PL40GtTTY6_-kB4qcrRLzulRmVtM1Ip4Ij">https://www.youtube.com/playlist?list=PL40GtTTY6_-kB4qcrRLzulRmVtM1Ip4Ij</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24c7217868b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Celebrating 250 Followers]]></title>
            <link>https://medium.com/@anil.java.story/celebrating-250-followers-78e8668af446?source=rss-98afcb09928f------2</link>
            <guid isPermaLink="false">https://medium.com/p/78e8668af446</guid>
            <dc:creator><![CDATA[anil gola]]></dc:creator>
            <pubDate>Sat, 03 Jun 2023 17:17:54 GMT</pubDate>
            <atom:updated>2023-06-03T17:17:54.623Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s nice to have 250 followers on Medium. I just want to thank all of them who have followed me.</p><p>I will keep adding blogs related to the Java ecosystem. So much is happening in the Java ecosystem. It’s an amazing time to be a part of this ecosystem as a Java developer.</p><p>Once again, thanks to everybody from the bottom of my heart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*YU5cNNmW0In_CTSFoEZEmw.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78e8668af446" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Embracing Virtual Threads in Spring Boot]]></title>
            <link>https://medium.com/@anil.java.story/embracing-virtual-threads-in-spring-boot-4140d3b8a5a?source=rss-98afcb09928f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4140d3b8a5a</guid>
            <category><![CDATA[virtual-threads]]></category>
            <category><![CDATA[springbootvirtualthread]]></category>
            <category><![CDATA[project-loom]]></category>
            <category><![CDATA[java20]]></category>
            <dc:creator><![CDATA[anil gola]]></dc:creator>
            <pubDate>Sat, 20 May 2023 17:59:45 GMT</pubDate>
            <atom:updated>2023-06-16T19:16:43.852Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*swGL-XtmORi9ck2QqnR9wQ.png" /></figure><p>In this blog, we will see how we can take leverage of project loom virtual threads in spring-boot. We will also do some load testing with the help of <strong>JMeter</strong> and see how response time for both virtual threads and normal threads.</p><p>First thing first, Virtual threads are a part of Project Loom.</p><p>Also, <strong><em>Loom does not accelerate your in-memory computations, for example parallel stream. This is not a goal of this project.</em></strong></p><p>We are looking at how to increase our application throughput with the same hardware available to us, i.e., using our CPU to its full potential, for which we are spending great bucks. As of now, we are able to utilise 2–3 percent of our CPU. I have discussed this in detail in this blog:</p><p><a href="https://medium.com/@anil.java.story/project-loom-virtual-threads-part-1-b17e327c8ba7">https://medium.com/@anil.java.story/project-loom-virtual-threads-part-1-b17e327c8ba7</a></p><p><strong><em>“I think Project Loom is going to kill Reactive Programming” — Brian Goetz (Java language architect)</em></strong></p><p>Let’s quickly setup our spring boot project.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;<br>         xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;<br>    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;<br>    &lt;parent&gt;<br>        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;<br>        &lt;version&gt;3.1.0&lt;/version&gt;<br>        &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;<br>    &lt;/parent&gt;<br>    &lt;groupId&gt;org.anil&lt;/groupId&gt;<br>    &lt;artifactId&gt;virtualthread&lt;/artifactId&gt;<br>    &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;<br>    &lt;name&gt;virtualthread&lt;/name&gt;<br>    &lt;description&gt;virtualthread&lt;/description&gt;<br>    &lt;properties&gt;<br>        &lt;java.version&gt;20&lt;/java.version&gt;<br>        &lt;tomcat.version&gt;11.0.0-M4&lt;/tomcat.version&gt;<br>    &lt;/properties&gt;<br>    &lt;dependencies&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;<br>        &lt;/dependency&gt;<br>        &lt;!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 --&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.apache.commons&lt;/groupId&gt;<br>            &lt;artifactId&gt;commons-lang3&lt;/artifactId&gt;<br>            &lt;version&gt;3.12.0&lt;/version&gt;<br>        &lt;/dependency&gt;<br><br>        &lt;!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --&gt;<br><br>        &lt;dependency&gt;<br>            &lt;groupId&gt;mysql&lt;/groupId&gt;<br>            &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;<br>            &lt;scope&gt;runtime&lt;/scope&gt;<br>            &lt;version&gt;8.0.33&lt;/version&gt;<br>        &lt;/dependency&gt;<br><br><br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>        &lt;/dependency&gt;<br><br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>            &lt;scope&gt;test&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>            &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>            &lt;version&gt;1.18.24&lt;/version&gt;<br>            &lt;scope&gt;compile&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;<br><br>    &lt;build&gt;<br>        &lt;plugins&gt;<br>            &lt;plugin&gt;<br>                &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>                &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;<br>            &lt;/plugin&gt;<br>            &lt;plugin&gt;<br>                &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;<br>                &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;<br>              &lt;configuration&gt;<br>                  &lt;compilerArgs&gt;<br>                      &lt;arg&gt;--enable-preview&lt;/arg&gt;<br>                      &lt;/compilerArgs&gt;<br>                  &lt;source&gt;20&lt;/source&gt;<br>                  &lt;target&gt;20&lt;/target&gt;<br>              &lt;/configuration&gt;<br><br>            &lt;/plugin&gt;<br>        &lt;/plugins&gt;<br>    &lt;/build&gt;<br><br>&lt;/project&gt;</pre><p>We need to enable preview features since Project Loom is in the preview stage. We have to wait for Java 21’s release for it to become a final feature. The PR has been merged in main branch of JDK. Consider reviewing 100,000 lines of codes. This many lines of code PR was raised, reviewed and merged.</p><pre>package org.anil.virtualthread;<br><br>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br>import org.springframework.boot.web.embedded.tomcat.TomcatProtocolHandlerCustomizer;<br>import org.springframework.context.annotation.Bean;<br><br>import java.util.concurrent.Executors;<br><br>@SpringBootApplication<br>@Slf4j<br>public class VirtualthreadApplication {<br><br>    public static void main(String[] args) {<br>        SpringApplication.run(VirtualthreadApplication.class, args);<br>    }<br><br>    @Bean<br>    public TomcatProtocolHandlerCustomizer&lt;?&gt; protocolHandlerVirtualThreadExecutorCustomizer() {<br>        return protocolHandler -&gt; {<br>            log.info(&quot;Configuring &quot; + protocolHandler + &quot; to use VirtualThreadPerTaskExecutor&quot;);<br>            protocolHandler.setExecutor(Executors.newVirtualThreadPerTaskExecutor());<br>        };<br>    }<br><br>}</pre><p>As of now, we need to configure virtual thread settings for the Tomcat server. In the future, this may be taken care of in auto-configuration itself.</p><pre>package org.anil.virtualthread;<br><br>import org.apache.commons.lang3.RandomStringUtils;<br>import org.apache.commons.lang3.RandomUtils;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.PostMapping;<br>import org.springframework.web.bind.annotation.RestController;<br><br>import java.util.List;<br><br>@RestController<br>public class HomeController {<br><br>    @Autowired<br>    ProductRepository productRepository;<br><br><br>    @GetMapping(&quot;/thread&quot;)<br>    public List&lt;Product&gt; checkThread() throws InterruptedException {<br>        Thread.sleep(1000);<br>        return productRepository.findAll();<br>    }<br><br><br>    @PostMapping(&quot;/save&quot;)<br>    public String saveProduct() throws InterruptedException {<br>        for(int i=0; i&lt; 1000; i++){<br>            Product product = new Product();<br>            product.setProductName(RandomStringUtils.randomAlphanumeric(5));<br>            product.setPrice(RandomUtils.nextLong(10,1000));<br>            product.setPrice(1L);<br>            productRepository.save(product);<br>        }<br>        return &quot;anil&quot;;<br>    }<br>}</pre><p>We have a <strong>GetMapping</strong> that returns all the products; we have 1000 <strong>Products</strong> in our database. We have made our thread sleep for 1 second. Let’s see our <strong>Product</strong> entity and <strong>ProductRepository</strong> as well.</p><pre>package org.anil.virtualthread;<br><br>import jakarta.persistence.Entity;<br>import jakarta.persistence.GeneratedValue;<br>import jakarta.persistence.GenerationType;<br>import jakarta.persistence.Id;<br>import lombok.Getter;<br>import lombok.Setter;<br><br>@Entity<br>@Getter<br>@Setter<br>public class Product {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br>    private String productName;<br>    private Long price;<br>}</pre><pre>package org.anil.virtualthread;<br><br>import org.springframework.data.jpa.repository.JpaRepository;<br><br>public interface ProductRepository extends JpaRepository&lt;Product,Long&gt; {<br>}</pre><p>Let’s see our application.yaml</p><pre>spring:<br>  datasource:<br>    driver-class-name: com.mysql.cj.jdbc.Driver<br>    maxIdle: 1<br>    timeBetweenEvictionRunsMillis: 60000<br>    hikari:<br>      connection-timeout: 60000<br>      maximum-pool-size: 10<br>      minimum-idle: 5<br>    url: jdbc:mysql://localhost:3306/todos<br>    testWhileIdle: true<br>    username: root<br>    password: root1234<br>    validationQuery: SELECT 1<br>  flyway:<br>    baseline-version: 0<br>    enabled: true<br>    validate-on-migrate: false<br>  jpa:<br>    database: mysql<br>    generate-ddl: true<br>    hibernate:<br>      ddl-auto: none<br>      format_sql: true<br>    show-sql: true</pre><p>Now, let’s first run the application by commenting on the following line: This will run our application on normal threads.</p><pre>package org.anil.virtualthread;<br><br>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br>import org.springframework.boot.web.embedded.tomcat.TomcatProtocolHandlerCustomizer;<br>import org.springframework.context.annotation.Bean;<br><br>import java.util.concurrent.Executors;<br><br>@SpringBootApplication<br>@Slf4j<br>public class VirtualthreadApplication {<br><br>    public static void main(String[] args) {<br>        SpringApplication.run(VirtualthreadApplication.class, args);<br>    }<br><br>//    @Bean<br>//    public TomcatProtocolHandlerCustomizer&lt;?&gt; protocolHandlerVirtualThreadExecutorCustomizer() {<br>//        return protocolHandler -&gt; {<br>//            log.info(&quot;Configuring &quot; + protocolHandler + &quot; to use VirtualThreadPerTaskExecutor&quot;);<br>//            protocolHandler.setExecutor(Executors.newVirtualThreadPerTaskExecutor());<br>//        };<br>//    }<br>}</pre><p>Now let’s setup our <strong>JMeter</strong>. We will have 1000 requests, which will ramp up in 3 seconds. And it will continue like this for a duration of 200 seconds. Every 3 seconds, 1000 GET (“/thread”) requests will be fired. We have also added a Response Time Graph Listener.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xWO_ONIa7Ohs_rq419SqGg.png" /></figure><p>Now let’s run our test and wait for 200 seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B_asy37c3Soy7xt2nmxPdQ.png" /></figure><p>In the graph, we can see that once the entire thread pool of Tomcat is utilised, the response time shoots from 3600 ms to 5200 ms. Since then, it has remained like that only as previous threads are released.</p><p>Now let’s run a load test with the virtual thread feature enabled.</p><pre>package org.anil.virtualthread;<br><br>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br>import org.springframework.boot.web.embedded.tomcat.TomcatProtocolHandlerCustomizer;<br>import org.springframework.context.annotation.Bean;<br><br>import java.util.concurrent.Executors;<br><br>@SpringBootApplication<br>@Slf4j<br>public class VirtualthreadApplication {<br><br>    public static void main(String[] args) {<br>        SpringApplication.run(VirtualthreadApplication.class, args);<br>    }<br><br>    @Bean<br>    public TomcatProtocolHandlerCustomizer&lt;?&gt; protocolHandlerVirtualThreadExecutorCustomizer() {<br>        return protocolHandler -&gt; {<br>            log.info(&quot;Configuring &quot; + protocolHandler + &quot; to use VirtualThreadPerTaskExecutor&quot;);<br>            protocolHandler.setExecutor(Executors.newVirtualThreadPerTaskExecutor());<br>        };<br>    }<br><br>}</pre><p>Now let’s run our test and wait for 200 seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YdDdj1lIJaIPP42vV-di7w.png" /></figure><p>Clearly, now the response time for concurrent 1000 requests is nearly just above 1000 ms and at some point shoots up to 1400 ms, which is far better than when we were using normal threads.</p><p>Clearly, when we need to utilise the underlying CPU to the fullest, we should start embracing virtual threads in our application, and suddenly we can see that the throughput of our application has increased manifold for the same hardware.</p><p><strong><em>This is much better than switching to reactive programming, which means rewriting all your code, which is very hard to learn first, then write, and even harder to debug and profile.</em></strong></p><p>In a nutshell, more users can use the application and get their response in the same time as the first user.</p><p>For how to create virtual threads in Project Loom, please check</p><p><a href="https://medium.com/@anil.java.story/project-loom-launching-10-million-threads-part-2-e0b2eb716b8b">Project Loom-Launching 10 million threads, Part 2</a></p><p><strong>My youtube channel:</strong></p><p><strong>Asynchronous Programming</strong> : <a href="https://www.youtube.com/playlist?list=PL40GtTTY6_-kmdeUznc1XeaTAb3zLlO6K">https://youtu.be/AHL2zuZ_5_k</a></p><p><strong>My talks in English </strong>: <a href="https://youtube.com/playlist?list=PL40GtTTY6_-ksLCcjKcHLALPEq66WHpwO">https://youtube.com/playlist?list=PL40GtTTY6_-ksLCcjKcHLALPEq66WHpwO</a></p><p><strong>My talks in Hindi</strong>: <a href="https://www.youtube.com/playlist?list=PL40GtTTY6_-kB4qcrRLzulRmVtM1Ip4Ij">https://www.youtube.com/playlist?list=PL40GtTTY6_-kB4qcrRLzulRmVtM1Ip4Ij</a></p><p><strong>If you like this blog, please clap and follow our channel. We keep posting interesting topics from Java Ecosystem. Also, you can support our team financially:</strong></p><p><a href="https://buy.stripe.com/6oE5m2e4d8jZ4OkbII"><strong>https://buy.stripe.com/6oE5m2e4d8jZ4OkbII</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4140d3b8a5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Structured Task Scope — New Concurrency Model]]></title>
            <link>https://medium.com/@anil.java.story/structured-task-scope-new-concurrency-model-c5fa38613f47?source=rss-98afcb09928f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5fa38613f47</guid>
            <category><![CDATA[project-loom]]></category>
            <category><![CDATA[new-concurrency-pattern]]></category>
            <category><![CDATA[structuredtaskscope]]></category>
            <category><![CDATA[concurrency-in-java]]></category>
            <category><![CDATA[java20]]></category>
            <dc:creator><![CDATA[anil gola]]></dc:creator>
            <pubDate>Tue, 16 May 2023 08:55:02 GMT</pubDate>
            <atom:updated>2023-06-16T19:17:14.469Z</atom:updated>
            <content:encoded><![CDATA[<h3>Structured Task Scope — New Concurrency Model in JVM</h3><p>Since the advent of virtual threads in Java, we have had a new and nice concurrency model introduced as <strong>StructuredTaskScope</strong>. We will see some patterns in this new model.</p><p>We need to know that with virtual threads, since they are very cheap, we don’t need to pool them. Also, we need to know that a virtual thread can pull its stack from the underlying platform thread to the heap when blocking for any operations and, when complete, can pin its stack to any of the available platform threads. <strong>This is new in Java, and it’s great.</strong></p><p>Consider the following code snippets:</p><pre> public static Weather readFromServerA() throws InterruptedException {<br>        Thread.sleep(RandomUtils.nextLong(1, 100));<br>        return new Weather(&quot;Partly Sunny&quot;, &quot;server-A&quot;);<br>    }<br>    public static Weather readFromServerB() throws InterruptedException {<br>        Thread.sleep(RandomUtils.nextLong(1, 100));<br>        return new Weather(&quot;Partly Sunny&quot;, &quot;server-B&quot;);<br>    }<br>    public static Weather readFromServerC() throws InterruptedException {<br>        Thread.sleep(RandomUtils.nextLong(1, 100));<br>        return new Weather(&quot;Partly Sunny&quot;, &quot;server-C&quot;);<br>    }</pre><p>The above code returns weather information. It mimics a server and returns information in 1–100 ms. Our requirement is to query all servers and get the results. The one that sends the result first will be considered, and our logic should be such that we should immediately cancel the other two requests (by interrupting them).</p><p>Let’s write this logic with the help of the <strong>StructuredTaskScope</strong> object.</p><pre>public static Weather readWeather() throws ExecutionException, InterruptedException, TimeoutException {<br>        try (var scope = new StructuredTaskScope.ShutdownOnSuccess&lt;Weather&gt;()){<br><br>           // need to call fork and pass runnables or callables<br>           scope.fork(() -&gt; Weather.readWeatherFromServerA());<br>           scope.fork(() -&gt; Weather.readWeatherFromServerB());<br>           scope.fork(() -&gt; Weather.readWeatherFromServerC());<br><br>           // now we block, blocking is cheap in virtual threas<br>           // so no issue here<br>           scope.join();<br><br>           Weather weather = scope.result();<br>           return weather;<br><br>}<br></pre><p>The pattern is quite simple; we have used the <strong>ShutdownOnSuccess</strong> variation of <strong>StructuredTaskScope</strong>, which is provided out of the box by the JVM.</p><p>We just submit the three tasks one by one to fetch weather from different servers. Method f<strong>ork()</strong> accepts <strong>callables</strong>.</p><p>Then we block with the help of scope. join(), and why do we block? Why not now? Blocking is cheap, and we should encourage developers to block.</p><p>Finally, we call the result method explicitly provided by the <strong>scope.result()</strong> method.</p><p>Now let’s see which request gets the result and which of the other two is cancelled.</p><pre>public static Weather readWeather() throws InterruptedException, ExecutionException {<br><br>        try(var scope = new StructuredTaskScope.ShutdownOnSuccess&lt;Weather&gt;();){<br><br>            scope.fork(() -&gt; Weather.readWeatherFromServerA());<br>            scope.fork(() -&gt; Weather.readWeatherFromServerB());<br>            scope.fork(() -&gt; Weather.readWeatherFromServerC());<br><br><br>            Future&lt;Weather&gt; futureA = scope.fork(Weather::readWeatherFromServerA);<br>            Future&lt;Weather&gt; futureB = scope.fork(Weather::readWeatherFromServerB);<br>            Future&lt;Weather&gt; futureC = scope.fork(Weather::readWeatherFromServerC);<br><br>            scope.join();<br><br>            System.out.println(&quot;futureA.state() = &quot; + futureA.state());<br>            System.out.println(&quot;futureB.state() = &quot; + futureB.state());<br>            System.out.println(&quot;futureC.state() = &quot; + futureC.state());<br><br>            var weather = scope.result();<br><br>           <br><br>            return weather;<br>        }<br><br>}<br><br> public static void main(String[] args) throws InterruptedException, ExecutionException {<br>       var weather = Weather.readWeather();<br><br>    }</pre><p>Let’s run this programme quite a few times.</p><pre>WARNING: Using incubator modules: jdk.incubator.concurrent<br>futureA.state() = FAILED<br>futureB.state() = FAILED<br>futureC.state() = SUCCESS</pre><pre>futureA.state() = FAILED<br>futureB.state() = SUCCESS<br>futureC.state() = FAILED</pre><p>We can see that different serves returned success, while the other two failed. It’s just for explanation; it’s technical code; we just need to query different servers as below.</p><pre>public static Weather readWeather() throws ExecutionException, InterruptedException, TimeoutException {<br>        try (var scope = new StructuredTaskScope.ShutdownOnSuccess&lt;Weather&gt;()){<br><br>           // need to call fork and pass callables<br>           scope.fork(() -&gt; Weather.readWeatherFromServerA());<br>           scope.fork(() -&gt; Weather.readWeatherFromServerB());<br>           scope.fork(() -&gt; Weather.readWeatherFromServerC());<br><br>           // now we block, blocking is cheap in virtual threas<br>           // so no issue here<br>           scope.join();<br><br>           Weather weather = scope.result();<br>           return weather;<br><br>}</pre><p>And by the way, the above code can be written even more clearly with the help of method references.</p><pre>public static Weather readWeather() throws InterruptedException, ExecutionException {<br>        try(var scope = new StructuredTaskScope.ShutdownOnSuccess&lt;Weather&gt;();){<br>            scope.fork(Weather::readWeatherFromServerA);<br>            scope.fork(Weather::readWeatherFromServerB);<br>            scope.fork(Weather::readWeatherFromServerC);<br>            scope.join(); <br>            var weather = scope.result();<br>            return weather;<br>        }<br>    }</pre><p><strong>How is it different from the ExecutorService?</strong></p><p>The ExecutorService lifecycle runs along with the lifecycle of the application. Once the application is started, the executor service framework starts and shuts down once the application is terminated.</p><p>But here, for every request call, StructuredTaskScope is created and destroyed as soon as we exit the method. We can do it because virtual threads are cheap — around 1000 times cheaper than platform threads.</p><p>Secondly, the above code can be written with the help of complete stage APIs, but with those frameworks, we need to welcome <strong>callback hells</strong> and long nesting of codes. 😉 <strong><em>Who likes callback hells? No body.</em></strong></p><p>We will look into more such patterns. It’s a completely new concurrency model, and we need to see exactly what patterns are going to become the norm, but I think that this is the pattern that we are going to use.</p><p>One reminder: it will work on Java 19 and above with the preview feature enabled.</p><p>This is just the starting, in coming blogs we will see some variations of <strong>StructuredTaskScope</strong>. Stay tuned.</p><p><strong>My youtube channel:</strong></p><p><strong>Asynchronous Programming</strong> : <a href="https://www.youtube.com/playlist?list=PL40GtTTY6_-kmdeUznc1XeaTAb3zLlO6K">https://youtu.be/AHL2zuZ_5_k</a></p><p><strong>My talks in English </strong>: <a href="https://youtube.com/playlist?list=PL40GtTTY6_-ksLCcjKcHLALPEq66WHpwO">https://youtube.com/playlist?list=PL40GtTTY6_-ksLCcjKcHLALPEq66WHpwO</a></p><p><strong>My talks in Hindi</strong>: <a href="https://www.youtube.com/playlist?list=PL40GtTTY6_-kB4qcrRLzulRmVtM1Ip4Ij">https://www.youtube.com/playlist?list=PL40GtTTY6_-kB4qcrRLzulRmVtM1Ip4Ij</a></p><p><strong>If you like this blog, please clap and follow our channel. We keep posting interesting topics from Java Ecosystem. Also, you can support our team financially:</strong></p><p><a href="https://buy.stripe.com/6oE5m2e4d8jZ4OkbII"><strong>https://buy.stripe.com/6oE5m2e4d8jZ4OkbII</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5fa38613f47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You don’t know Lazy Initialization Spring Data JPA]]></title>
            <link>https://medium.com/@anil.java.story/you-dont-know-lazy-initialization-spring-data-jpa-601b525d791c?source=rss-98afcb09928f------2</link>
            <guid isPermaLink="false">https://medium.com/p/601b525d791c</guid>
            <category><![CDATA[spring-data-jpa]]></category>
            <category><![CDATA[lazy-loading-hibernate]]></category>
            <category><![CDATA[lazy-initialization]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[eager-loading]]></category>
            <dc:creator><![CDATA[anil gola]]></dc:creator>
            <pubDate>Tue, 25 Apr 2023 09:14:11 GMT</pubDate>
            <atom:updated>2023-06-06T06:30:25.682Z</atom:updated>
            <content:encoded><![CDATA[<p>This might look like you know all the stuff related to eager and lazy initialization, but bear with me; you will surely know one or two things by reading this blog.</p><p>Consider the following code snippet:</p><pre>@Entity<br>@Getter<br>@Setter<br>public class Employee{<br>   <br>      @Id<br>      @GeneratedValue(strategy = GenerationType.IDENTITY)<br>      private Long Id,<br>      private String empName;<br><br>      @ManyToOne<br>      @JoinColumn(name = &quot;employees&quot;)<br>      private Department department;<br>}<br><br>@Entity<br>@Getter<br>@Setter<br>public class Department{<br>       @Id<br>       @GeneratedValue(strategy = GenerationType.IDENTITY)<br>       private Long id,<br>       private String deptName;<br>       @OneToMany(mappedBy = &quot;department&quot;)<br>       private List&lt;Employee&gt; employees = new ArrayList&lt;&gt;();<br>}</pre><pre>public interface DepartmentRepository extends JpaRepository&lt;Department, Long&gt; {<br>}</pre><p>Simple stuff. Two entities have <strong>OneToMany</strong> relationships and one department repository.</p><p>Now let’s fetch the department by ID.</p><pre>class Service{<br>      <br>     @Autowired<br>     DepartmentRepository departmentRepository;<br>   <br>     public void fetchDepartment(){<br>            Department department = departmentRepository.findById(1L).get();<br><br>    }<br>    <br><br>}</pre><p>Now lets dissect the line</p><pre>Department department = departmentRepository.findById(1L).get();</pre><p>If we check what we have in the department when our debugger is at the above line, we can see that <strong>id</strong> and <strong>deptName</strong>, but when we try to see <strong>employees</strong>, we will see some proxy object that contains nothing. In the console, we will see the below SQL query getting fired.</p><pre>select id, dept_name from department</pre><p>But the hibernate has not fetched any of the <strong>employees</strong> belonging to the department. This is what lazy loading is all about. <strong>OnetoMany</strong> is by default lazy, and there is no need to provide <strong>fetch = FetchType. <em>LAZY. ManyToMany</em></strong><em> </em>is also Lazy by default, but <strong>OneToOne</strong> is eager by default.</p><p>Why hibernate has put <strong>OnetoOne</strong> in Eager category? Let’s ponder it. Hibernate has no issue finding any number of columns in a single row. When we do <strong>findById</strong>, since <strong>OnetoOne</strong> will only correspond to a single row in <strong>Employee </strong>table, it can happily join one row of <strong>Employee</strong> with one row of <strong>Department</strong>, and eventually, the result will contain only one row. It can be brought in without affecting the performance much, even though we only require the department name.</p><p>Now in the case of <strong>OnetoMany</strong>, one <strong>Department</strong> row will correspond to multiple rows of <strong>Employee</strong>, and Hibernate will be hesitant to fetch multiple rows of employees (which can go to 1000s) while fetching the department. It would require the user to explicitly mention that he/she wants employees along with department. This can be done with the help of <strong>fetchType=FetchType.EAGER</strong>. If we see the logs, we can see the following query hit by hibernate:</p><pre>select id, deptName from Department where id = ?<br><br>select id, empName from Employee where department_id in (?)</pre><p>We can do better here. Instead of calling <strong>fetchType=FetchType.EAGER</strong>, we may leave <strong>fetchType</strong> as default and fetch the employees when we actually require it. This can be achieved by just calling</p><pre>department.getEmployees()</pre><p>The above line will make another database connection and fire the query to fetch employees for that department.</p><pre>select id, empName from Employee where department_id in (?)</pre><p>Sometimes we do get a <strong>LazyInitializationException</strong>. We will try to get that exception with the following code snippet:</p><pre> @Autowired<br>    DepartmentRepository departmentRepository;<br><br>    @Bean<br>    public CommandLineRunner demo() {<br>        return (args) -&gt; {<br>            for (var department : departmentRepository.findAll()) {<br>                System.out.println(department.getEmployees());<br>            }<br>        };<br>    }</pre><p>As soon as we start the application, we get following output in console</p><pre>Caused by: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: org.anil.testcontainers.test1.entity.Department.employees: could not initialize proxy - no Session<br> at org.hibernate.collection.spi.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:631) ~[hibernate-core-6.1.6.Final.jar:6.1.6.Final]<br> at org.hibernate.collection.spi.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:218) ~[hibernate-core-6.1.6.Final.jar:6.1.6.Final]<br> at org.hibernate.collection.spi.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:611) ~[hibernate-core-6.1.6.Final.jar:6.1.6.Final]<br> at org.hibernate.collection.spi.AbstractPersistentCollection.read(AbstractPersistentCollection.java:136) ~[hibernate-core-6.1.6.Final.jar:6.1.6.Final]<br> at org.hibernate.collection.spi.PersistentBag.toString(PersistentBag.java:584) ~[hibernate-core-6.1.6.Final.jar:6.1.6.Final]<br> at java.base/java.lang.String.valueOf(String.java:4218) ~[na:na]<br> at java.base/java.io.PrintStream.println(PrintStream.java:1047) ~[na:na]<br> at org.anil.testcontainers.TestContainersApplication.lambda$demo$0(TestContainersApplication.java:26) ~[classes/:na]<br> at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:767) ~[spring-boot-3.0.2.jar:3.0.2]<br> ... 5 common frames omitted</pre><p>What the heck is going on here? When we try to fetch the employees, the hibernate is no longer firing the query and throwing the <strong>LazyInitializationException</strong>. This is because we are outside the transactional scope. Once we have fetched the department by using <strong>findAll, </strong>hibernate<strong> </strong>closed the session and when we try to fetch employees, there can be no way Hibernate knows how to fetch employees. So getter(in this case getEmployees()) should be called in open session. Call in Service method annotated with <strong>@Service</strong> and use <strong>@Transaction</strong> on method to make sure that we have session open.</p><p>Hope you get the gist.</p><p><strong>My YouTube channel (in Hindi): </strong><a href="https://youtu.be/Z8HKMvcvx-g"><strong>https://youtu.be/Z8HKMvcvx-g</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=601b525d791c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>