<?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 Mohamed Anees on Medium]]></title>
        <description><![CDATA[Stories by Mohamed Anees on Medium]]></description>
        <link>https://medium.com/@mohamedanees6?source=rss-54cf0142c89a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*JZdoklGTD_bl8aDAWAXOPw.jpeg</url>
            <title>Stories by Mohamed Anees on Medium</title>
            <link>https://medium.com/@mohamedanees6?source=rss-54cf0142c89a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 03:14:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mohamedanees6/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[Beware of  tracePinnedThreads : How It Can Freeze Your App!]]></title>
            <link>https://medium.com/@mohamedanees6/beware-of-tracepinnedthreads-how-it-can-freeze-your-app-831d29fd54fa?source=rss-54cf0142c89a------2</link>
            <guid isPermaLink="false">https://medium.com/p/831d29fd54fa</guid>
            <category><![CDATA[java-virtual-threads]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[virtual-threads]]></category>
            <category><![CDATA[thread-pool]]></category>
            <dc:creator><![CDATA[Mohamed Anees]]></dc:creator>
            <pubDate>Thu, 07 Nov 2024 06:14:52 GMT</pubDate>
            <atom:updated>2024-11-07T06:14:52.886Z</atom:updated>
            <content:encoded><![CDATA[<h3>Beware of tracePinnedThreads : How It Can Freeze Your App!</h3><p>It was a nice evening, Unit Tests and Integration Tests were all green and we were prepping ourselves to do a Production deployment. Right after deployment, we saw that readiness check started failing and eventually the service started faltering anything above 3000 RPM.</p><p>Let’s dive in.</p><h3>Event 0: Deployment</h3><p>We deployed the changes around midnight where there was comparatively lesser traffic, and the changes were substantial. The whole deployment process was smooth, and was uneventful.</p><h3>Event 1: Waking up to Alerts!</h3><p>We got a PagerDuty Alert by morning (even before peak traffic) for pods restarting for the service we deployed the previous day. Not a right way to start the day at all 😢 Something was off and we headed straight to our Monitoring tools — Prometheus &amp; Grafana in our case.</p><h3>Event 2: What happened to Metrics?</h3><p>We were puzzled to see that there were some gaps in Grafana visualisation itself. Uh! No!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S1HqKIEIofCjam7NQjr4MA.png" /><figcaption>Screenshot showing gaps in Metrics</figcaption></figure><p>This was because Prometheus follows a Pull based Metric Collection. <a href="https://prometheus.io/blog/2016/07/23/pull-does-not-scale-or-does-it/">This</a> is an amazing read to know more.</p><p>But in our case, Pull based collection failed completely as shown above. This is explained later in this post.</p><h3>Event 3: Reverting the deployment</h3><p>Developers hate early morning. And more so if Pods are restarting like crazy and metrics do not have anything. We hit the “Revert” button hoping to slumber till daily team check-in — prepare to fight off Product/Business team on why the feature delivery is delayed.</p><h3>Event 4: The Nightmare in next 10 mins</h3><p>We resolved the incident manually, and dropped off the call. In next 10 mins, the service again started fumbling (Not at usual traffic yet, as other callers had the circuit breakers tripped already) . The story went back to exactly how it was after Event 2, but this time we did not have the magic button (“Revert”) to undo everything.</p><p>Time was ticking where the service would reach its usual traffic of 20k RPM, and peaks at 40–50k RPM. It would be a catastrophe at that scale if service is not able to keep up current 3k RPM.</p><h3>Event 5: Increasing Memory and CPU resources, Number of Pods etc.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/0*52LSanUmKwVZ0KOn.gif" /></figure><p>Of no use. Let’s not talk about it.</p><h3>Event 6: Mystery Unfolds</h3><p>We have added a seemingly uninteresting property between our code deployments.</p><pre>-Djdk.tracePinnedThreads=full</pre><p>We did not think ever that a JVM Argument, which is used to do something completely unrelated would cause these issues. As we did not have any other changes pushed at all, we had to quickly read about this while in middle of an outage.</p><p>We stumbled upon <a href="https://bugs.openjdk.org/browse/JDK-8322846">JDK-8322846</a> which looked like the cause of the issue. We immediately removed this argument, and service went back to work as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*sal66BOMkyxtf88Z.gif" /></figure><h3>Time for RCA(s):</h3><p>We now know that JDK-8322846 was the culprit. So, we decided to deep dive a bit on the bug and the incidents surrounding this outage to understand them better.</p><h3>RCA 1: Grafana Not Scraping Metrics</h3><p>Since the application was not responding, the readiness and liveness probes were timing out. K8s was keen on restarting the pods, and causing restarts throughout. It is likely that metrics endpoint that is used as target by Prometheus also timed out / failed. We tried out with a demo controller and hitting actuator endpoint in parallel.</p><p>Below is the Controller code,</p><pre>private val lock = Any()<br><br>    @GetMapping(&quot;/test-thread-pinning&quot;)<br>    fun testThreadPinning(): Callable&lt;String&gt; {<br>        return Callable {<br>            synchronized(lock) {<br>                try {<br>                    Thread.sleep(3000)<br>                    &quot;Task completed by synchronized block ${Thread.currentThread().name}&quot;<br>                } catch (e: InterruptedException) {<br>                    println(&quot;Interrupted&quot;)<br>                    &quot;Interrupted&quot;<br>                }<br>            }<br>        }<br>    }</pre><p>And, hitting the actuator through ApacheBench.</p><pre>ab -n 1 -c 1 http://localhost:4001/actuator/health<br>This is ApacheBench, Version 2.3 &lt;$Revision: 1913912 $&gt;<br>Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/<br>Licensed to The Apache Software Foundation, http://www.apache.org/<br><br>Benchmarking localhost (be patient)...apr_pollset_poll: The timeout specified has expired (70007)</pre><p>As expected, the actuator endpoints too became unresponsive. Hence, no metrics added to Prometheus.</p><h3>RCA 2: Understanding JDK-8322846</h3><p>We dig a bit deeper into JDK code, and found where exactly this is being printed.</p><pre>private static class VThreadContinuation extends Continuation {<br>//omitted<br>        @Override<br>        protected void onPinned(Continuation.Pinned reason) {<br>            if (TRACE_PINNING_MODE &gt; 0) {<br>                boolean printAll = (TRACE_PINNING_MODE == 1);<br>                PinnedThreadPrinter.printStackTrace(System.out, printAll);<br>            }<br>        }<br>//omitted<br>    }</pre><p>As we can see, PinnedThreadPrinter is responsible for printing the stacktrace, and a shared object System.out is passed in as an argument.</p><p>PinnedThreadPrinter has an Object called Hashes which basically keeps track of the hash of stack trace that was already printed to avoid printing the same trace multiple times.</p><pre>    @SuppressWarnings(&quot;serial&quot;)<br>    private static class Hashes extends LinkedHashMap&lt;Integer, Boolean&gt; {<br>        boolean add(int hash) {<br>            return (putIfAbsent(hash, Boolean.TRUE) == null);<br>        }<br>        @Override<br>        protected boolean removeEldestEntry(Map.Entry&lt;Integer, Boolean&gt; oldest) {<br>            // limit number of hashes<br>            return size() &gt; 8;<br>        }<br>    }</pre><p>Since this extends LinkedHashMap - which in itself is not Thread-Safe and no extra efforts are made in Hashes to make this Thread-Safe as well. Hence, synchronized block was used to print the hash.</p><pre><br>        stack.stream()<br>            .filter(f -&gt; (f.isNativeMethod() || f.getMonitors().length &gt; 0))<br>            .map(LiveStackFrame::getDeclaringClass)<br>            .findFirst()<br>            .ifPresentOrElse(klass -&gt; {<br>                int hash = hash(stack);<br>                Hashes hashes = HASHES.get(klass);<br>                synchronized (hashes) {<br>                    if (hashes.add(hash)) {<br>                        printStackTrace(stack, out, printAll);<br>                    }<br>                }<br>            }, () -&gt; printStackTrace(stack, out, true)); </pre><p>So, synchronized block in already pinned thread can cause the threads to be blocked again here.</p><p>If the application contains a lot of executions where Thread Pinning happens, it can again meet here with a severe contention of printing them. This would have severe impact on the overall performance of the application and leading to all Carrier Threads become pinned for a longer time. And, we do not have a lot of Carrier Threads to play around with and the system eventually succumbs with a lot of requests waiting to check whether or not to print the stack trace.</p><p>We were somewhat convinced that we found some contention in already pinned code execution.</p><h3>But wait, the quest is not complete. Below is the actual RCA:</h3><p>This test does not complete running at all (Code taken from the fix of the JDK bug),</p><pre>void testContention() throws Exception {<br>        class C1 {<br>            synchronized void print() {<br>                System.out.println(&quot;hello&quot;);<br>            }<br>        }<br>        class C2 {<br>            synchronized void print() {<br>                System.out.println(&quot;hello&quot;);<br>            }<br>        }<br>        class C3 {<br>            synchronized void print() {<br>                System.out.println(&quot;hello&quot;);<br>            }<br>        }<br>        class C4 {<br>            synchronized void print() {<br>                System.out.println(&quot;hello&quot;);<br>            }<br>        }<br>        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {<br>            executor.submit(() -&gt; {<br>                new C1().print();<br>            });<br>            executor.submit(() -&gt; {<br>                new C2().print();<br>            });<br>            executor.submit(() -&gt; {<br>                new C3().print();<br>            });<br>            executor.submit(() -&gt; {<br>                new C4().print();<br>            });<br>        }<br>    }</pre><p>Here we have only 4 print statements, and this defeats our earlier assumption that Carrier Threads are pinned and leading to application to becoming unresponsive. But, why does this test fail without much contention?</p><p>We did not have any clue, and wrote to Alan Bateman, the person who actually made the fix to understand more about the bug.</p><p>Quoting from his reply over email.</p><blockquote>If you attempt to park when pinned then printing the stack trace will be done in the context of a critical operation (parking). Printing a stack trace requires executing a lot of code and this may park too, the result is nested parking.</blockquote><p>Now things are somewhat clear on why this incident happened exactly.</p><p>If the virtual thread parks while printing the stack trace (due to IO contention) then it works like a nested park where the thread state is never restored since it stemmed already from PARKING — There is no more explanation present anywhere on this nor we can derive from code as these are written inside Native JVM code.</p><p>Nested parking can be alarming for high throughput systems causing unpredictable latency. This condition can also potentially lead to deadlock.</p><p>Let’s take an oversimplified example of the JDK code,</p><pre><br>  private final Object lock1 = new Object();<br><br>    public void criticalSectionDemo() {<br>        synchronized (lock1) { <br>            if (TRACE_PINNING_MODE == 1) {<br>                printSomething();<br>            }<br>        }<br>    }</pre><p>printSomething() can also make the thread to Park (Wait) on unavailability of the IO resources.</p><p>Let’s now simulate a deadlock:</p><ol><li>Thread 1 enters criticalSectionDemo() and acquires a monitor.</li><li>Thread 2 acquires a monitor on the IO resource and wants to now enter criticalSectionDemo().</li></ol><p>In this case, Thread 1 waits (Parks) for IO resource monitor to be released by Thread 2 and Thread 2 waits for lock1 monitor held by Thread 1 to be released resulting in deadlock.</p><p>Of course, in practice, this deadlock would be more complex and involve multiple threads and an indirect circular wait. And there we put an end to our quest this time. Fin!</p><p>How exciting the life of Developer is! ⭐️ Happy Coding! 😃</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=831d29fd54fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ElasticSearch Node Hotspots— How we averted an Outage?]]></title>
            <link>https://medium.com/@mohamedanees6/elasticsearch-node-hotspots-how-we-averted-an-outage-28dc8bc953fa?source=rss-54cf0142c89a------2</link>
            <guid isPermaLink="false">https://medium.com/p/28dc8bc953fa</guid>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[hotspots]]></category>
            <dc:creator><![CDATA[Mohamed Anees]]></dc:creator>
            <pubDate>Sun, 11 Aug 2024 11:32:54 GMT</pubDate>
            <atom:updated>2024-08-11T11:32:54.067Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BYiwytR3SPhdBlel" /><figcaption>Photo by <a href="https://unsplash.com/@timrael?utm_source=medium&amp;utm_medium=referral">Timur Kozmenko</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>ElasticSearch is one of the commonly used data store in many systems. We’ll not deep dive into the use cases nor what ES is capable of in this article.</p><p>Rather, this article would focus on how we averted a production outage, and the journey while debugging it.</p><h3>What is a hotspot?</h3><p>ElasticSearch usually runs on multiple nodes (usually referred to as Cluster) in Production Environments for HA and scalability. Hotspot is when some of the nodes are taking up most of the work and other nodes are comparatively running without much to do. This usually leads to degraded performance in any distributed datastore.</p><h3>The ElasticSearch Setup:</h3><p>We’re using Elastic Cloud on K8s (ECK) <a href="https://www.elastic.co/guide/en/cloud-on-k8s/current/index.html">https://www.elastic.co/guide/en/cloud-on-k8s/current/index.html</a> which is deployed to our own K8s cluster. This would later form a very important piece of the problem we are looking at. Read on!</p><h3>The Problem:</h3><p>The problem we were facing in our cluster was the uneven disk usage across nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ens0vUHbEwFM_Oi6MvmsnA.png" /><figcaption>Figure showing uneven disk usage in ES Cluster</figcaption></figure><p>As soon as we saw this, we understood there is some hotspot issue in our cluster. We scoured through the official documentation and performed the first step written over <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/hotspotting.html">here</a>.</p><pre>GET _cat/allocation?v&amp;s=node&amp;h=node,shards,disk.percent,disk.indices,disk.used</pre><p>Unsurprisingly, we were having uneven distribution of shards leading to higher disk usage on our Node 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*BIdsMMHeBzvxaP6POY6zUA.png" /><figcaption>Image showing shards being allocated in an uneven manner</figcaption></figure><h3>Step 0: Finding what’s special with Node 0</h3><p>To find this, we performed</p><pre>GET _cat/nodes?v&amp;s=master,name&amp;h=name,master,node.role,heap.percent,disk.used_percent,cpu</pre><p>to see if there is any issues with node role which can make Node 0 special.</p><p>The output was a dead end though.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*nuX3tM5D-cAKpKrm1psKZw.png" /></figure><p>All the nodes were having dim role. Nothing special here.</p><blockquote>dim = d (data node), i (ingest node), m (master-eligible node)</blockquote><h3>Step 1: Finding a pattern on already allocated shards</h3><p>Seemingly disappointed with no previlege given to Node 0, our next option was to go to drawing board and find a pattern. We listed down all the indexes present in all shards determined to find something out of this.</p><pre>GET /_cat/shards</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*KLIpMgk-rFzAT2_5pjhh3A.png" /></figure><p>We have ILM policies in place to rollover the indexes. To our surprise, whenever a new index is created for a day, most of the allocations were done on Node 0 and is <em>almost exactly twice</em> that of what is being allocated to Node -1 and Node-2, and this cannot be a coincidence.</p><h3>Step 2: Time to Deep Dive! Node 0 is special, But How?</h3><p>We performed</p><pre>GET _cluster/allocation/explain<br>{<br>  &quot;index&quot;: &quot;XXXXXXXXXXXXXXXXXXXXXXX-2024-8-7&quot;,<br>  &quot;shard&quot;: 0,<br>  &quot;primary&quot;: true<br>}</pre><p>on 10 recently indexes which are already created in our ES. We were focusing on <strong>node_allocation_decisions </strong>primarily on the response.</p><pre>{<br>    &quot;decider&quot;: &quot;awareness&quot;,<br>    &quot;decision&quot;: &quot;NO&quot;,<br>    &quot;explanation&quot;: &quot;there are [2] copies of this shard and [2] values for attribute [k8s_node_name] ([i-XXXXXXXXXXX0c925, i-XXXXXXXXXC84fd] from nodes in the cluster and no forced awareness) so there may be at most [1] copies of this shard allocated to nodes with each value, but (including this copy) there would be [2] copies allocated to nodes with [node.attr.k8s_node_name: i-XXXXXXXXXX84fd]&quot;<br>}</pre><p>This gave us a hunch that something might be wrong with k8s_node_name since the allocation deciders were telling only about two k8s_node_name but never the third one.</p><h3>Step 3: Eureka! The Shard Allocation Awareness</h3><blockquote>Would highly recommend you to go though this to understand what’s happening below : <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-cluster.html#shard-allocation-awareness">https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-cluster.html#shard-allocation-awareness</a></blockquote><p>We ran</p><pre>GET /_cluster/settings?include_defaults=true</pre><p>to know all the cluster settings. And finally we found,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*5KazKDPy6ENjXSqoAy79Hw.png" /></figure><p>k8s_node_name was mentioned as one of the awareness attribute to consider while allocation of shard to a node.</p><p>On further checking where are our nodes running in our K8s Cluster, we found the culprit.</p><pre>Node 0 = Instance : i-XXXXXXXXXXXXXX4fd<br>Node 1 = Instance : i-XXXXXXXXXXXXXX925<br>Node 2 = Instance : i-XXXXXXXXXXXXXX925</pre><p>Node 1 and 2 were running on same K8s node!!! And, since k8s_node_name was one of the awareness attribute ES could not allocate any index only including Node-1 and 2.</p><h3>Step 4: The fix!</h3><p>Happiest step of debugging is when we close all the tabs, and tell DevOps team to fix 😅. As next step, DevOps team made tweaks to Node Affinity while allocating ES nodes to make sure no two ES nodes are allocated to same EKS node.</p><p>And, finally!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*K6A7NA-Ab5m_Boq5Jt6QIQ.png" /><figcaption>After fixing node affinity</figcaption></figure><p>And that’s how we averted an Outage. Fin!</p><p>How exciting the life of Developer is! ⭐️ Happy Coding! 😃</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28dc8bc953fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Sequences & Collections —Looking at Developer’s Common Mistake in PR]]></title>
            <link>https://medium.com/@mohamedanees6/kotlin-sequences-collections-looking-at-developers-common-mistake-in-pr-0850d4c47983?source=rss-54cf0142c89a------2</link>
            <guid isPermaLink="false">https://medium.com/p/0850d4c47983</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[pull-request-reviews]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[code-review]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Mohamed Anees]]></dc:creator>
            <pubDate>Mon, 18 Mar 2024 03:52:00 GMT</pubDate>
            <atom:updated>2024-03-18T03:52:00.018Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Inspiration:</strong></h3><p>As a Senior Developer in my team, I review a lot of pull requests every day from fellow developers. And, I see this as one common mistake I see developers make and likely go unnoticed in code reviews too.</p><p>And, this article was born from one of my PR comments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qtuVB0cK6VHCLQVM" /><figcaption>Photo by <a href="https://unsplash.com/@ikukevk?utm_source=medium&amp;utm_medium=referral">Kevin Ku</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Code #0 → {Green Valley of Java Streams}:</h3><p>Most of the Backend Engineers in my team have Java background. They use various Stream operations in everyday code, and are damn good at it.</p><p>Usually, all the code somewhat looks like this over simplified example while iterating through any Collection.</p><p><em>Data Class — Person :</em></p><pre>class Person {<br>    public Integer age;<br>    public String name;<br>    public Person(Integer age, String name){<br>        this.age = age;<br>        this.name = name;<br>    }</pre><p><em>Service Code — To find first Person having age &gt; 10 from a list of Person.</em></p><pre>List&lt;Person&gt; people = new ArrayList&lt;&gt;();<br>people.add(new Person(20,&quot;Anees&quot;));<br>people.add(new Person(10,&quot;Wall-E&quot;));<br>System.out.println(<br>   people.stream()<br>         .filter(person -&gt; person.age &gt; 10)<br>         .findFirst()<br>);</pre><p>This is pretty much how we usually process a Stream of Person Collection and find first person who has age &gt; 10.</p><p>If we look closely here, Java has always provided us the option to perform ONLY lazy evaluation through Streams.</p><blockquote>Streams are lazy; computation on the source data is only performed when the terminal operation is initiated, and source elements are consumed only as needed. — JavaSE Docs.</blockquote><p>Here, findFirst() is a <strong>short circuiting terminal operation</strong>. This means that as soon as one element is found, the rest of the stream is not processed and the element is returned after getting wrapped in an Optional.</p><p>This means person.age was accessed only once in our sample example.</p><h3>{Code #1 -&gt; Falling into Kotlin Darkness}</h3><p>The same code is written as below in Kotlin,</p><pre> val myList = listOf(Person(20, &quot;Anees&quot;), Person(10, &quot;Wall-E&quot;))<br> print(myList.filter { it.age &gt; 10 }.firstOrNull())</pre><p>Are you able to find the issue here?</p><p>Mostly not. Unit Tests too shows all Green since it would still find the same Person.</p><p>Let’s deep dive here since this exactly what I see as a mistake (Unintended behaviour but same output).</p><p>Kotlin provides two ways to perform evaluation as against Java which supports only Lazy evaluation on Streams.</p><p>— Lazy Evaluation (Through Sequences)</p><p>— Eager Evaluation (Through Iterable of Collections)</p><p>I’d like to focus on this <a href="https://kotlinlang.org/docs/sequences.html">documentation</a> of Kotlin Sequences.</p><blockquote>When the processing of an Iterable includes multiple steps, they are executed eagerly: each processing step completes and returns its result – an intermediate collection. The following step executes on this collection.</blockquote><p>Here we have done a Eager Evaluation 😑 , many people think firstOrNull provides short-circuiting but that is NOT the case here.</p><p>The code for firstOrNull looks like below</p><pre>public fun &lt;T&gt; List&lt;T&gt;.firstOrNull(): T? {<br>    return if (isEmpty()) null else this[0]<br>}</pre><p>Shocked? 🤕 There is no short-circuit or any magic with this code. Lets prove this by adding some loggers to our Service code.</p><pre>    val myList = listOf(Person(20, &quot;Anees&quot;), Person(10, &quot;Wall-E&quot;))<br>    val ageGreaterThan10: (Person) -&gt; Boolean = { person -&gt;<br>        println(&quot;I am called for $person&quot;)<br>        person.age &gt; 10<br>    }<br>    print(myList.filter { ageGreaterThan10(it) }<br>        .firstOrNull())</pre><p>Output is</p><pre>I am called for Person(age=20, name=Anees)<br>I am called for Person(age=10, name=Wall-E)<br>Person(age=20, name=Anees)</pre><p>We have ended up calling the predicate for all the elements in the list though the first element itself was enough to give output in this case.</p><h3>Code#2 : {Day of Revelation}</h3><p>Lets fix the service code now with Sequences.</p><pre>val myList = listOf(Person(20, &quot;Anees&quot;), Person(10, &quot;Wall-E&quot;))<br>val ageGreaterThan10: (Person) -&gt; Boolean = { person -&gt;<br>    println(&quot;I am called for $person&quot;)<br>    person.age &gt; 10<br>}<br>print(myList.asSequence()<br>    .filter { ageGreaterThan10(it) }<br>    .firstOrNull())</pre><p>The only addition here is asSequence on the list. The output is as intended.</p><pre>I am called for Person(age=20, name=Anees)<br>Person(age=20, name=Anees)</pre><p>Lets again look at same Kotlin documentation</p><blockquote>Sequence performs all the processing steps one-by-one for every single element.</blockquote><blockquote>So, the sequences let you avoid building results of intermediate steps, therefore improving the performance of the whole collection processing chain.</blockquote><p>This is almost equivalent to operating on Streams in Java and is the intended behaviour which you most probably wanted.</p><h3>Conclusion:</h3><p>Wherever you are iterating through a Collection, make sure you have lazy evaluation for short-circuiting operations for larger collections and if it is computationally heavy or involving some IO.</p><p>Also, consider this before you blindly add asSequence everywhere.</p><blockquote>The lazy nature of sequences adds some overhead which may be significant when processing smaller collections or doing simpler computations.</blockquote><p>As always in Software Engineering, it depends.</p><p>Further Read: <a href="https://kotlinlang.org/docs/sequences.html#sequence-processing-example">https://kotlinlang.org/docs/sequences.html#sequence-processing-example</a></p><p>Thanks for staying with me till here 🎉</p><p>Find me here on <a href="https://www.linkedin.com/in/mohamedaneesa/">LinkedIn</a> 😃 Happy to connect 🍀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0850d4c47983" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I despise (Mostly) using Loops and fell in love in Sequences!]]></title>
            <link>https://medium.com/@mohamedanees6/why-i-despise-mostly-using-loops-and-fell-in-love-in-sequences-c8beba57f3ad?source=rss-54cf0142c89a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8beba57f3ad</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[programming-tips]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Mohamed Anees]]></dc:creator>
            <pubDate>Sat, 10 Feb 2024 19:39:05 GMT</pubDate>
            <atom:updated>2024-02-11T00:35:42.204Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pa1Pn8VHrM1Tv-kT" /><figcaption>Photo by <a href="https://unsplash.com/@tine999?utm_source=medium&amp;utm_medium=referral">Tine Ivanič</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Usually all programs contain loops. I was a good and happy developer once who was writing a lot of for loop as everyone else. I’ll state a few problems on looping and why I started using Sequences and fell in love with it 💌 And, I highly recommend you to do so as well.</p><p>Let’s look at below piece of code,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UJD0REvUJkoNCi3w7uB-pw.png" /><figcaption>Figure 1 — Loops and mess!</figcaption></figure><p>This is a fairly simple program which creates a list of Person and collects all the names ending with lo and prints it.</p><h3>Problem 1: Variable Naming of result .</h3><p>As a developer, naming variables is the most difficult task in writing any piece of code. For this trivial task, I am now forced to name the list I am going to collect as result (Refer, Figure 1).</p><p>We see such code in almost all codebases, where you define a variable prefixed usually with result and return this.</p><p>I hate seeing result since , resultcan be intermittent or final during execution of program. So, result is indeed tricky.</p><p>I’ve seen finalResult, result1 , result2 and so on in same method.</p><p>Let’s write this using Sequence now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sA9Vlb1bEyw0Cnm6O7YpPA.png" /><figcaption>Figure 2 — The Saviour, Sequence</figcaption></figure><p>Immediately, we feel now the code is more concise and easy to read. Writing with Sequences, I am now free from naming variables! Hurray! 😍</p><h3>Problem 2: Indentation 👽</h3><p>If we compare Figure 1 &amp; 2. One more thing we notice is that Figure 2 is easy on eyes. No open and Close curly braces to enclose code boundaries and nested braces. What a relief to debug!</p><p>One thing to keep in mind here though is that, we should make sure that the Predicate is not too complicated. If yes, it could be extracted as shown below. (This does not make sense now since our Predicate is very simple. But this is to just show the idea)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TykZNTTXRDfT0FnK4XpfUA.png" /><figcaption>Figure 3 — Extracting Predicates</figcaption></figure><h3>Problem 3 : Errors on Extensions</h3><p>Lets consider the same code where we want to collect all names in a List ending with lo . You now got a new feature that one of the Person can be null. And you quickly write this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t_fEL2UDCrWb2-PPMQ9Zrw.png" /><figcaption>Figure 4 — Loops with null check</figcaption></figure><p>Now you have got multiple issues. There are multiple ugly ? questioning indirectly your programming skills, and there is == operator.</p><p>Also, there is a risk of writing == false over here, which is terrible (If we do not have Unit Tests, this may go to Production too).</p><p>Let’s do the same thing with Sequence,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VMMlqGco-a_nKuZDyiph7g.png" /><figcaption>Figure 5 — Alternate to null safe operator, filterNotNull</figcaption></figure><p>We just added filterNotNull() in front of filter() . That is all! We have not written any logical operator, nor comparison operator to check for null. Thereby no errors. More importantly, we did not touch the originalfilter at all!</p><h3>Problem 4: `break` statements</h3><p>Of all the things that complicates our code, break and continue should top the list. These are uncanny things which confuses me whenever I review or write code.</p><p>Let’s complicate our problem statement that we have to collect first 2 names ending with lo .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*EMN33LY6dm4e7KCY-OLDYA.png" /><figcaption>Figure 6 — Dreaded break statement</figcaption></figure><p>There are two problems here, We have increased the level of nesting by adding another if condition to collect only 2 elements. And, added a break statement. You need to trace visually to nearest loop to know what is it breaking out from.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aJO7Y3CrJVw1Buo9otCKbg.png" /><figcaption>Figure 7 — Using take in a Sequence</figcaption></figure><p>take() hides all the complexity from you. Takes only how much you need. Genius, Isn’t it?</p><h3>Problem 5: No Support for Nested Collections</h3><p>Lets go rogue. You have a third party API which gives a `listOf(listOf(listOf(Person)))`.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R1-dNIQSudN_TOH3xWWcoQ.png" /></figure><p>You would need to repeat the loops as deep as they are nested. You are adding more pain to your teammates because some third party API developer got drunk while writing his contracts.</p><p>Let’s ease the pain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*32KdBrCjE_WQeS-rpBo8DA.png" /><figcaption>Figure 8 — Super Amazing Sequence Flatteners</figcaption></figure><h3><strong>Problem 6: Need to Review a lot of Developer Code</strong></h3><p>As a reviewer, the lesser code I see, I become happy in approving it.</p><p>With Sequence , I am definitely reviewing lesser code. Basically, I can skim through filter and map methods only (for the examples above) because other things are just language features which I have no doubts on.</p><p>Thanks for staying with me till here 🎉 Happy Sequencing your Collections!</p><p>Find me here on <a href="https://www.linkedin.com/in/mohamedaneesa/">LinkedIn</a> 😃</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8beba57f3ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep dive into Java Parallel Streams]]></title>
            <link>https://medium.com/@mohamedanees6/deep-dive-into-java-parallel-streams-6f3ef805cead?source=rss-54cf0142c89a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f3ef805cead</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[parallel-processing]]></category>
            <category><![CDATA[java-stream-api]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Mohamed Anees]]></dc:creator>
            <pubDate>Sun, 04 Feb 2024 09:55:38 GMT</pubDate>
            <atom:updated>2024-02-04T09:55:38.172Z</atom:updated>
            <content:encoded><![CDATA[<p>Usually when I ask fellow developers on how would you process a Stream in parallel, the first immediate response is to use parallelStream() . But many of us stumble on how it actually works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aoFwk9MbPO_L8i_Y" /><figcaption>Photo by <a href="https://unsplash.com/@sseeker?utm_source=medium&amp;utm_medium=referral">Stormseeker</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Lets look at some code samples and how it works internally.</p><blockquote>Driver code is written in Kotlin. But internally have used Java Streams.</blockquote><blockquote>Written with Java 21, and Kotlin 1.9.21. But Java 8+ should behave the same.</blockquote><h3>Driver Code:</h3><pre>data class Person(val name: String, val age: Int) {<br>}<br><br>fun main() {<br>    val personList: MutableList&lt;Person&gt; = mutableListOf();<br>    IntStream.rangeClosed(1, 1000).forEach { personList.add(Person(&quot;RandomName:${it}&quot;, it)) }<br>    val names = personList.parallelStream().map { it.name }.collect(Collectors.toList())<br>    println(names)<br>}</pre><p>It is a fairly simple program. It creates 1000 people, and collects the name of the created people to List and prints the list.</p><h3>What happens in parallelStream()</h3><blockquote>Below section contains a lot of Internal details, I advise the readers to go through this section very slowly. I know it is hard to grasp. Read this article multiple times, and feel free to drop me a message on LinkedIn for any doubts.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QRw52jPpNjmMwsonZc3C_w.png" /></figure><p>As you can see from the source code, parallelStream() returns a Stream. Nothing fancy at all. Now, who performs the actual split and parallel operations?</p><p>Enters, <strong>Spliterator and Lazy Execution.</strong></p><h3>What is a Spliterator?</h3><p>It is impossible to deep dive into parallelStream without understanding what is a Spliterator.</p><p>As you’ll see towards the end of this article, Spliterator methods are used to split and fork multiple tasks to be executed in parallel.</p><p>This is logically same as Iterator, but has ability to split the elements.</p><pre><br>fun main() {<br>    val personList: MutableList&lt;Person&gt; = mutableListOf();<br>    IntStream.rangeClosed(1, 10).forEach { personList.add(Person(&quot;RandomName:${it}&quot;, it)) }<br>    val original = personList.spliterator()<br>    val split1 = original.trySplit()<br>    val split2 = original.trySplit()<br>    println(&quot;-----------Original--------------------------&quot;)<br>    original.forEachRemaining { println(it.name) }<br>    println(&quot;-----------Split1-------------------------&quot;)<br>    split1.forEachRemaining{ println(it.name) }<br>    println(&quot;-----------Split2--------------------------&quot;)<br>    split2.forEachRemaining{ println(it.name) }<br>}</pre><p>The output looks like this,</p><pre>-----------Original--------------------------<br>RandomName:8<br>RandomName:9<br>RandomName:10<br>-----------Split1-------------------------<br>RandomName:1<br>RandomName:2<br>RandomName:3<br>RandomName:4<br>RandomName:5<br>-----------Split2--------------------------<br>RandomName:6<br>RandomName:7</pre><p>As you can see Spliterator is able to split a list (Not create multiple copies, You just get a view of the split lists) into multiple parts. Below is a gist of how this is done for ArrayList.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eaOQlPfYYBOFcgSwdgqqtA.png" /></figure><p>You get a view from lo to mid every time you call trySplit. And the actual List is left untouched. It keeps a track of the current index as well to aid in further split.</p><p>expectedModCount is used to check for ConcurrentModificationException. It is out of scope of this article to discuss about it.</p><h3>What is Lazy Execution?</h3><p>Streams in Java are inherently laziness-seeking! They try to avoid parsing through the elements of the Stream as late as possible. There are two types of operations</p><ul><li>Intermediate Operations — Which produces Stream after passing through it.</li><li>Terminal Operations — Which produces Value/causes some side-effect.</li></ul><p>Lets focus on the line we have written,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*QBxWCu8lTUwe207DAeAvOg.png" /></figure><p>as you can see, parallelStream() and map() returns Stream. So these are intermediate operations and will be executed lazily later.</p><p>Let’s look at collect()</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gPYkTUOaS1BE39c3BDMq4w.png" /></figure><p>As you can see in this source code, there are some processing involved based on whether the pipeline is parallel or not. I am not going to dwell into details of how Collectors work. But, the overall point over here is that it is a <strong>terminal-operation</strong> and needs to take care of all the intermediate operations that has happened so far on the Stream pipeline.</p><p>There has to be <strong>only one Terminal Operation throughout your Stream</strong> <strong>pipeline</strong> since the Stream ends here. Now you know who actually needs to take care of all the chaining that has happened so far in the Stream. It is the Terminal Operations you trypically do at the end!</p><p>Let’s look at evaluate method in AbstractPipeline now (Look at else condition in last image).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LDhvNUgkS9Tqws2Bn_5mLg.png" /></figure><p>As you can see here, there is again a condition to handle the Stream in parallel or sequential order.</p><blockquote>When the terminal operation is initiated, the stream pipeline is executed sequentially or in parallel depending on the orientation of the stream on which it is invoked. — JavaDoc.</blockquote><h3>Enters The Dragon!</h3><p>If we look at source code of evaluateParallel method, you would see</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QqGcYgwAsOui2wHf7EKjmA.png" /></figure><p>We are constructing a ReduceTask . There are other similar implementations like FindTask, ForEachTask and so on. Here is exactly where the processing happens.</p><p>The master mind behind all these is AbstractTask . This is where Fork-Join Tasks are created and a tree for Spliterator is maintained.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gFv6WmlDiAPWPXixrf5CPQ.png" /></figure><p>As you can see here, a fork join pool is used to compute the actual computations.</p><p>For curious people, here is the source code of `compute()` method in AbstractTask .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LUPvLFj4ANxDrVAytF7dZA.png" /></figure><p>As you can see here, trySplit is called repeatedly on the original Spliterator, and tasks are forked.</p><p>Thanks for staying with me till here 🎉</p><p>Find me here on <a href="https://www.linkedin.com/in/mohamedaneesa/">LinkedIn</a> 😃</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f3ef805cead" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Virtual Machine (JVM) is not a Virtual Machine? ]]></title>
            <link>https://medium.com/@mohamedanees6/java-virtual-machine-jvm-is-not-a-virtual-machine-3ce57f621800?source=rss-54cf0142c89a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ce57f621800</guid>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[jvm-architecture]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Mohamed Anees]]></dc:creator>
            <pubDate>Sun, 21 Jan 2024 03:43:58 GMT</pubDate>
            <atom:updated>2024-01-21T03:43:58.421Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eopETT-3jcM6JNnL" /><figcaption>Photo by <a href="https://unsplash.com/@lazycreekimages?utm_source=medium&amp;utm_medium=referral">Michael Dziedzic</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When someone tells me JVM is Java Virtual Machine, I ask them what type of VM it is and they go blank. This had happened (is happening too!) with experienced people who have spent 10+ years in Java based Web Application Development who I have interviewed for.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nQ1Hb21eXa2XxHGb" /><figcaption>Photo by <a href="https://unsplash.com/@jcgellidon?utm_source=medium&amp;utm_medium=referral">JC Gellidon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This sets the stage for this article. Let’s do a deep dive on what is a VM and why JVM is named as JVM 😉 Or the naming is incorrect? 🤔</p><p>First, lets understand the types of VM</p><ul><li>System Virtual Machine</li><li>Process Virtual Machine</li></ul><h3>System Virtual Machine:</h3><blockquote>System virtual machines are capable of virtualizing a full set of hardware resources, including a processor (or processors), memory and storage resources and peripheral devices. A virtual machine monitor (VMM, also called hypervisor) is the piece of software that provides the abstraction of a virtual machine. — Source: <a href="https://en.wikipedia.org/wiki/Popek_and_Goldberg_virtualization_requirements">Wikipedia</a>.</blockquote><p>Guess, this definition is top-notch and most concise I’ve ever seen. But sadly this is present in some other article and not the main VM page.</p><p>I’ll explain the above lines with a simple example. Consider that I have a Windows Laptop and I want develop software that runs on some Linux Distribution (say, Ubuntu). I’d install a Hypervisor (Type 2) which simply runs as a process on my Windows installed laptop. Hypervisor takes care of hiding Ubuntu from my original Windows OS.</p><p><em>PS : More details on Hypervisor are omitted for brevity. I’d suggest you to read about them. We’d be diverging too much from JVM if we discuss about Hypervisors.</em></p><h3>Process Virtual Machines</h3><p>This runs as a normal application in your host machine. The process is started on your machine, and this dies within your machine, and the host OS is aware of what this process does.</p><p>JVM makes sure that your class files runs within it, and runs under same single process. Whenever you start your command with `java`, you are essentially creating a JVM and asking it to run your class file.</p><p>One machine can have multiple JVMs running as long as your hardware supports it. For explaining this in simple terms, This is what happens when you start your Spring Boot web applications on different ports. Imagine you are having Order Service running on port 8080 and Cart Service running on port 8081, you are now having two JVM running as two different processes totally unaware that other one is running (As long as they don’t ask for same port or communicate through HTTP) under your OS. If your OS exits, JVM also gets killed like any other process. (This does not happen on Type 1 Hypervisor based VM, OS exists independently on a single host).</p><p>Below is the screenshot from JRE download page (<a href="https://www.java.com/en/download/manual.jsp">https://www.java.com/en/download/manual.jsp</a>), which shows multiple OS, and you are forced to choose your JRE (Ultimately JVM) based on your OS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*5q1AnscvIpdViizlQHVeZg.png" /></figure><p>This shows you that there is some dependency on underlying system/OS on the JVM selection itself.</p><p>The Over-simplified version of this amazing architecture looks like below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NnS5wYRml0WTotaX3yJ9yQ.png" /></figure><h3>Key Learnings:</h3><ul><li>JVM is NOT system/OS independent.</li><li>Java class files are independent of JVM it runs on (Java version should match as well). This is why you can build once, run anywhere.</li><li>JVM is not a System Virtual Machine, but a Process Virtual Machine.</li></ul><p>JVM creators are cannot go wrong with naming a core part of Java ecosystem, can they? 🍀</p><p>Hope this article helped you clear this once and for all! Next time if someone asks you what JVM is, you can reply that it is Java Process based Virtual Machine (We’ll call it as JPVM instead of JVM 😛).</p><p>Happy learning 💚</p><p>—</p><p>You can find me on LinkedIn <a href="https://www.linkedin.com/in/mohamedaneesa/">here</a> 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ce57f621800" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot 3.x & Java 21 — Simplistic Migration Handbook]]></title>
            <link>https://blog.stackademic.com/spring-boot-3-x-java-21-simplistic-migration-handbook-d93053978d27?source=rss-54cf0142c89a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d93053978d27</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Mohamed Anees]]></dc:creator>
            <pubDate>Sun, 14 Jan 2024 07:04:14 GMT</pubDate>
            <atom:updated>2024-01-16T04:17:48.386Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v-U9_37fFw5b1pt5" /><figcaption>Photo by <a href="https://unsplash.com/@altumcode?utm_source=medium&amp;utm_medium=referral">AltumCode</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Pre-read:</p><p><a href="https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-3.0-Migration-Guide">https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-3.0-Migration-Guide</a></p><p>I know you haven’t read that fully. Spring + Java team has put in a lot of effort to make this a easy process so that you need not think about a thousand things. They already did most of the heavylifting for you! 😍</p><p>Here I’ll cover some practical aspects that you would face on migration from Java 11 to Java 21 (But this can be used for other versions too).</p><h4><strong>IntelliJ IDEA Upgrade issues</strong></h4><p>Since this is most commonly used IDE for Java + Kotlin development, not upgrading it before embarking on the journey caused a lot of issues for me.</p><p>One most notable issue was TimeUnit enum in java.util.concurrent package was not recognised for me throughout my codebase. This totally caught me wondering, and I ended up checking my local setup, then reinstalling JDK and installing other distributions of JDK 21 🤦‍</p><p>Read more about this here,</p><p><a href="https://blog.jetbrains.com/idea/2023/09/intellij-idea-2023-2-2/">https://blog.jetbrains.com/idea/2023/09/intellij-idea-2023-2-2/</a></p><p><a href="https://stackoverflow.com/questions/77551293/intellij-idea-jdk-21-issue-with-java-util-concurrent-package-timeunit-class">https://stackoverflow.com/questions/77551293/intellij-idea-jdk-21-issue-with-java-util-concurrent-package-timeunit-class</a></p><h4>SDKMAN! for the win</h4><p>Setting up Java 21 on local where you’ve other version is tricky. You’d face issues with JAVA_HOME and finding the compiler and switching back to Java 21 and forth is time-consuming.</p><p>SDKMAN reduces your time in setting up JAVA_HOME and other system + Java ecosystem based variables whenever you make a switch between JDK versions. It truly is a blessing.</p><p>Read more about this here, IMO this is a must have in every Java + Kotlin Dev’s local.</p><p><a href="https://sdkman.io/">Home | SDKMAN! the Software Development Kit Manager</a></p><h4>Migration from Javax to Jakarta EE</h4><p>This is already written in Spring boot migration guide mentioned in the pre-read. But there may be some issues during migration like <a href="https://github.com/quarkusio/quarkus/issues/33973">https://github.com/quarkusio/quarkus/issues/33973</a>.</p><p>I simply did a find and replace for all javax.* packages to jakarta.*. It worked flawlessly without any issues (However, I have not tried Persistence related packages). Highly recommended to use this <a href="https://github.com/openrewrite/rewrite-migrate-java/tree/main">https://github.com/openrewrite/rewrite-migrate-java/tree/main</a> for migration.</p><p>You are mostly good to go if you get</p><pre>[INFO] --- rewrite:5.18.0:dryRun (default-cli)  myservice ---<br>[INFO] Using active recipe(s) []<br>[INFO] Using active styles(s) []<br>[INFO] Applying recipes would make no changes. No patch file generated.</pre><p>on performing</p><pre>mvn rewrite:dryRun</pre><p>Huge shoutout to Eclipse Foundation and open source enthusiasts for making this almost seamless! 🎉 ❤️</p><h4>Using Spring Properties Migrator</h4><p>Add below dependency to your app, and start the application, it shows the properties that were migrated/deprected in latest version of spring-boot.</p><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>  &lt;artifactId&gt;spring-boot-properties-migrator&lt;/artifactId&gt;<br>  &lt;scope&gt;runtime&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><p>The errors look like</p><pre>Property source &#39;Config resource &#39;class path resource [application-local.properties]&#39; via location &#39;optional:classpath:/&#39;&#39;:<br> Key: management.metrics.export.prometheus.enabled<br>  Line: 14<br>  Replacement: management.prometheus.metrics.export.enabled</pre><p>This eliminates your need to go through documentations for finding the equivalent replacement.</p><h4>Migrating Tests to JUnit 5</h4><p>Read <a href="https://junit.org/junit5/docs/current/user-guide/#migrating-from-junit4-tips">https://junit.org/junit5/docs/current/user-guide/#migrating-from-junit4-tips</a>. This is self-explanatory and mostly involves changing the imports if needed.</p><h4>Trailing Slash based path matching</h4><p>Though this is mentioned in Spring migration guide, it is worth mentioning it since it may break your E2E tests or Production too.</p><p>For curious people, There is a lengthy discussion on <a href="https://github.com/spring-projects/spring-framework/issues/28552">https://github.com/spring-projects/spring-framework/issues/28552</a> and <a href="https://github.com/spring-projects/spring-framework/issues/31366">https://github.com/spring-projects/spring-framework/issues/31366</a></p><p>Issue #31366 aims to make the default behaviour of this to false. But, it is worth testing this yourself.</p><h4>Log4j2 version upgrade</h4><p>Upgrade log4j2.version in your project to 2.19.0. Anything less than this is not supported in Spring Boot 3.x</p><h4>Springfox Deprecation</h4><p>If you are using Springfox dependencies, you’d face the below error</p><pre>Caused by: java.lang.ClassNotFoundException: javax.servlet.http.HttpServletRequest<br> at jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641) ~[?:?]<br> at jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188) ~[?:?]<br> at java.lang.ClassLoader.loadClass(ClassLoader.java:526) ~[?:?]<br> at java.lang.Class.forName0(Native Method) ~[?:?]<br> at java.lang.Class.forName(Class.java:534) ~[?:?]<br> at java.lang.Class.forName(Class.java:513) ~[?:?]<br> at sun.reflect.generics.factory.CoreReflectionFactory.makeNamedType(CoreReflectionFactory.java:114) ~[?:?]</pre><p>Remove all io.springfox dependencies, and add below dependency</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springdoc&lt;/groupId&gt;<br>    &lt;artifactId&gt;springdoc-openapi-starter-webmvc-ui&lt;/artifactId&gt;<br>    &lt;version&gt;2.3.0&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>Refer <a href="https://stackoverflow.com/a/75326796/6140314">https://stackoverflow.com/a/75326796/6140314</a> for more details on the problem.</p><p>You can refer to <a href="https://springdoc.org/#migrating-from-springfox">https://springdoc.org/#migrating-from-springfox</a> for helping in migration.</p><p>These are some issues I faced when I moved a project from Java 11 to 21. You’d face even lesser issues if you are moving from 17 to 21. Hope this helped you in easy migration. Happy coding ⭐️ 🤞</p><h3>Stackademic</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq">X</a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> |</strong> <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d93053978d27" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/spring-boot-3-x-java-21-simplistic-migration-handbook-d93053978d27">Spring Boot 3.x &amp; Java 21 🚀— Simplistic Migration Handbook</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Characteristic abstraction help you in long run — From the eyes of a Java developer]]></title>
            <link>https://medium.com/swlh/how-characteristic-abstraction-help-you-in-long-run-from-the-eyes-of-a-java-developer-2282340f8cf5?source=rss-54cf0142c89a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2282340f8cf5</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[better-programming]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[code-quality]]></category>
            <dc:creator><![CDATA[Mohamed Anees]]></dc:creator>
            <pubDate>Sat, 07 Dec 2019 07:29:53 GMT</pubDate>
            <atom:updated>2019-12-16T17:09:42.317Z</atom:updated>
            <content:encoded><![CDATA[<h3>How Characteristic abstraction help you in long run — From the eyes of a Java developer</h3><p>Characteristic abstraction is nothing but containing the characteristics of the objects of a particular class in itself.</p><p>Let us consider we have a simple class,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35355828257135638806cd08df399184/href">https://medium.com/media/35355828257135638806cd08df399184/href</a></iframe><p>And let’s move on to our imaginary country where all Person is either Male/Female. And if age of Male and Female is above 20 and 18 respectively, he/she is considered as Major.</p><p>Let us approach this problem with traditional loops,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c253c71ecade056edd653da98119f786/href">https://medium.com/media/c253c71ecade056edd653da98119f786/href</a></iframe><p>A little better with plain Java 8 Streams,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88f3588ddf95f03d5cc8d97026dd13a3/href">https://medium.com/media/88f3588ddf95f03d5cc8d97026dd13a3/href</a></iframe><p>However, after extracting the Predicate , this can look even better</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b7d131c3231706f0ac7300f145e2e36/href">https://medium.com/media/2b7d131c3231706f0ac7300f145e2e36/href</a></iframe><p>We have now made the best we can do with Streams. But, there is one caveat to this approach. It is the place where we have defined isMajor() method. This is defining the characteristic of the Person objects and ideally should be present in Person class. So, our updated Person class would look like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4811d4da2b55769b108ecbe07cbb91e/href">https://medium.com/media/d4811d4da2b55769b108ecbe07cbb91e/href</a></iframe><p>This maybe a minor change. But, it brings amazing reduction in the code complexity and in maintenance of the code. Suppose, if you now want to change the major-ing age of Female person from 18 to 20. It would just require a change in Person class and nowhere else in your codebase.</p><p>Also, our code looks much neater</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/389bfc1115d95429b03030a7d4613d2a/href">https://medium.com/media/389bfc1115d95429b03030a7d4613d2a/href</a></iframe><p>Also, this would help at large with inheritance. Let’s have a class Engineer extends Person . Now if you want to amend isMajor() only for Engineers, all that we need to do is override the isMajor() method in the Person class.</p><p>So, henceforth if you see any characteristic that is common to all the objects of a particular class, please start to accommodate it inside the class.</p><p><strong><em>Also, Think thrice before creation of Utility Classes,</em></strong><strong><em>PersonUtility.java to do this. There is a wrong trend/pattern in making Utility classes instead of performing characteristic abstraction.</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9e8a95014dd7ce9e2df274c73059c3b/href">https://medium.com/media/f9e8a95014dd7ce9e2df274c73059c3b/href</a></iframe><p>Isn’t this looking clumsy/unnatural to read? You’d probably want to check what isMajor is doing in PersonUtility because it is a separate class and could do anything under its whims! Also, this would be a different hard story to explain if multiple inherited classes need to Override the isMajor() behaviour and our PersonUtility is just screwed for life. 😂</p><p>So, Nothing more. Nothing less. Just Abstract it right! 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2282340f8cf5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/how-characteristic-abstraction-help-you-in-long-run-from-the-eyes-of-a-java-developer-2282340f8cf5">How Characteristic abstraction help you in long run — From the eyes of a Java developer</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Streams in Java 8? Things you must know of!]]></title>
            <link>https://medium.com/@mohamedanees6/using-streams-in-java-8-things-you-must-know-of-1ca2c937c0f?source=rss-54cf0142c89a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ca2c937c0f</guid>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Mohamed Anees]]></dc:creator>
            <pubDate>Sun, 01 Dec 2019 05:14:44 GMT</pubDate>
            <atom:updated>2019-12-01T14:03:15.246Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using Streams in Java 8? 3 Little Things you must watch out for!</h3><p>Streams is a welcome addition in Java 8. Of course, they were a bit overwhelming at first to know about them. But, once you got a knack of it, it can be hard to avoid them. Here are the things which you must consider before you write stream() in your code.</p><h4>Why not stream() everything?</h4><p>I’ve seen an amateur programmer, who was keen in converting all loops into Stream in our codebase. Also, I know of some companies which refrain from using traditional for loops for looping. So, why not St(c)ream?</p><h4>Because they can be wonderful-one-liners :)</h4><p>Here is a very simple collection of Integer that needs to be squared and collected in a new List and the traditional approach would be,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a53c67dd0a27898324d2f2751804a09/href">https://medium.com/media/4a53c67dd0a27898324d2f2751804a09/href</a></iframe><p>And the Streams,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c51beeece1c252269ca9df752bc1fdf/href">https://medium.com/media/0c51beeece1c252269ca9df752bc1fdf/href</a></iframe><p>So far so good. The code looks more neat and concise (Which Java developers were craving for so long!). Streams are always a welcome-addition to the language. We need to just tell it what to do, rather than how to do it.</p><h4>So, what to watch-out for?</h4><h4>1. Always `null` first - Even with Streams!</h4><p>What if the Collection of Integer had some null values? Developer must take care of it like,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cc8722a42ecb1026c3370606a2c46b2/href">https://medium.com/media/4cc8722a42ecb1026c3370606a2c46b2/href</a></iframe><p>I’ve seen potential code-blocks that ignore null values in a Collection with Stream.</p><h4>2. Using Collectors.toMap() Without Merge Strategy!</h4><p>Let us have Person POJO, having name and age as its fields.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16df04f2169abfdac2d646ed5c0f21b2/href">https://medium.com/media/16df04f2169abfdac2d646ed5c0f21b2/href</a></iframe><p>You might expect it to produce output like</p><blockquote>{Anees=Name is : Anees, Age is : 30, Hannah=Name is : Hannah, Age is : 20}</blockquote><p>which must have happened since you are trying to insert two entries into Map with same Key .</p><p>But, surprisingly, this throws an Exception</p><p><em>Exception in thread “main” java.lang.IllegalStateException: Duplicate key Name is : Anees, Age is : 10 at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133 at java.util.HashMap.merge(HashMap.java:1254)</em></p><p>What has gone wrong! Because it uses merge() in java.util.Map to collect it as a Map internally. It is not streaming the List and calling the put() as most developers expect it.</p><p>This can be fixed with adding a Merge Strategy as below,</p><blockquote>Map&lt;String, Person&gt; personNameMap = people.stream().collect(Collectors.toMap(Person::getName, Function.identity(), (oldKey, newKey) -&gt; newKey));</blockquote><h4>3. Converting stream() to parallelStream()</h4><p>Parallelising Stream is one of the most easiest thing to do. Because, the developer thinks just converting stream() to parallelStream() would get the job done. Easy peasy!</p><p>But it is a lot more than that. The developer must make sure there are no side-effects of making it parallel .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f212e5096a742e9efabe82fb3f27ca5/href">https://medium.com/media/9f212e5096a742e9efabe82fb3f27ca5/href</a></iframe><p>Let’s make it parallel? Because I need the list of 0 to 100 FASTER!</p><p>Okay, here I made it parallel. In a jiffy and it is so easy!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8177d21146cb38e89644f9e6af78d90a/href">https://medium.com/media/8177d21146cb38e89644f9e6af78d90a/href</a></iframe><p>But wait! Can ArrayList take care of parallelism? No, and here is the output</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81e2cab2514b5f113583c6fac534f222/href">https://medium.com/media/81e2cab2514b5f113583c6fac534f222/href</a></iframe><p>Pretty hard to digest is it? Because ArrayList is not ThreadSafe. In order to do that, you’ll need to fix it up like, wrapping the List with List.synchronizedList() or you’ll need to use forEachOrdered() . So, if you are making a stream to parallel, think thrice whether all your data structures are adhering to it and is it really such a costly operation to perform!</p><p>Alas! Try not to do these henceforth :) Happy Sc(t)reaming!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ca2c937c0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>