<?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 Vivek Malhotra on Medium]]></title>
        <description><![CDATA[Stories by Vivek Malhotra on Medium]]></description>
        <link>https://medium.com/@malhotra.vivek?source=rss-cac2c9397ec8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lZH0tjSfIwnAT4ebrUmdGA.jpeg</url>
            <title>Stories by Vivek Malhotra on Medium</title>
            <link>https://medium.com/@malhotra.vivek?source=rss-cac2c9397ec8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 16:12:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@malhotra.vivek/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[Optimize JVM for kubernetes (part 1)]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://blog.devops.dev/optimize-jvm-for-kubernetes-part-1-e0d8b7ace00a?source=rss-cac2c9397ec8------2"><img src="https://cdn-images-1.medium.com/max/1024/1*EGwiDr1GZfAQJeWRNQc3JQ.png" width="1024"></a></p><p class="medium-feed-snippet">Today we would discuss how JVM actually behaves when running in a container environment like kubertenes. I would also share how we setup&#x2026;</p><p class="medium-feed-link"><a href="https://blog.devops.dev/optimize-jvm-for-kubernetes-part-1-e0d8b7ace00a?source=rss-cac2c9397ec8------2">Continue reading on DevOps.dev »</a></p></div>]]></description>
            <link>https://blog.devops.dev/optimize-jvm-for-kubernetes-part-1-e0d8b7ace00a?source=rss-cac2c9397ec8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0d8b7ace00a</guid>
            <category><![CDATA[jvm-memory]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[jvm]]></category>
            <dc:creator><![CDATA[Vivek Malhotra]]></dc:creator>
            <pubDate>Tue, 25 Feb 2025 07:02:01 GMT</pubDate>
            <atom:updated>2025-02-26T14:20:11.835Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Immutability in Java records vs Kotlin data classes]]></title>
            <link>https://medium.com/@malhotra.vivek/immutability-in-java-records-vs-kotlin-data-classes-464d7bb9a11c?source=rss-cac2c9397ec8------2</link>
            <guid isPermaLink="false">https://medium.com/p/464d7bb9a11c</guid>
            <category><![CDATA[kotlin-data-class]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[java-records]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[immutability]]></category>
            <dc:creator><![CDATA[Vivek Malhotra]]></dc:creator>
            <pubDate>Fri, 20 Oct 2023 21:33:00 GMT</pubDate>
            <atom:updated>2023-11-20T13:00:44.746Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cb6JGjqIn9e1VyDIinx7Cg.png" /></figure><h3>Introduction</h3><p>Every Java developer from early 2000s who has written a lot of data classes would have agreed that we had to write a lot of repetitive code just to implement the basic necessities expected from data classes. A simple data class in Java prior to jdk 14 was written somewhat as:</p><pre>public class Person {<br>    public final String name;<br>    public final int age;<br>    public Person(String name, int age) {<br>        this.name = name;<br>        this.age = age;<br>    }<br><br>    @Override<br>    public boolean equals(Object o) {<br>        if (this == o) return true;<br>        if (o == null || getClass() != o.getClass()) return false;<br>        Person person = (Person) o;<br>        return age == person.age &amp;&amp; Objects.equals(name, person.name);<br>    }<br><br>    @Override<br>    public int hashCode() {<br>        return Objects.hash(name, age);<br>    }<br><br>    @Override<br>    public String toString() {<br>        return &quot;Person{&quot; +<br>               &quot;name=&#39;&quot; + name + &#39;\&#39;&#39; +<br>               &quot;, age=&quot; + age +<br>               &#39;}&#39;;<br>    }<br>}</pre><p>Though data classes were around in Koltin 1.0 since 2016 not everyone Java developer could leverage that. Firstly you either needed to write and compile Kotlin code along side Java in your commercial Project or also seek a vote in the team to even make a move towards Kotlin.</p><p><strong>Records were introduced in Java 16 as a feature in 2021 after the </strong><a href="https://openjdk.org/jeps/395"><strong>JEP 395</strong></a><strong>. They were proposed with similar intent to help developers create simple and dumb data classes. However the JEP also talks about carrier of immutable data. </strong>And this is what made me write this article.</p><h4>Kotlin data classes</h4><p>Kotlin was the first to introduce compact way to write data classes. The main purpose was to generate initialisation in canonical constructor, equals(), hashCode() and toString(). The kotlin version of your Person data class in Kotlin will be as concise as:</p><pre>data class Person(val name: String, val age: Int)</pre><p>This was a leap forward and saved so much time writing a simple data class. Not just this kotlin also</p><ul><li>generates copy constructors</li><li>lets you define default values for the fields in your data class</li></ul><h4>Java Records</h4><p>Records when introduced in Java was a breath of fresh air. Like finally we have something like kotlin data classes. So a record would look like</p><pre>public record Person(String name, int age) {<br>    <br>}</pre><p>And this is good concise declaration of a data class.</p><h4>Java Records vs Kotlin data classes</h4><p>Under the hood Java records does a lot of things like Kotlin data class.</p><ul><li>Auto generated equals(), hashCode(), toString().</li><li>initialization of fields in constructor</li></ul><p>What Java records does not do and makes it fall short to Kotlin are</p><ul><li>copy constructors</li><li>allow default values to fields</li></ul><p>When we started writing backend applications in Kotlin we felt these features of data classes in kotlin really helped speed up our development time. However there is one thing which Java records are good at is enforcing immutability.</p><h4>Shallow immutability in Kotlin data classes</h4><p>Kotlin data classes only enforce shallow immutability and it is harded to enforce full immutability pattern on them. An example is let us we have a class Train which has a Set of stations:</p><pre>data class Train(val name: String, val stations: List&lt;String&gt;)</pre><p>This contruct provides shallow immutability so if you instantiate a train instance with a mutable list of stations like</p><pre>fun main(){<br>    val stations = mutableListOf(&quot;Mumbai&quot;)<br>    val train = Train(name=&quot;TR01&quot;, stations = stations)<br>    stations.add(&quot;Pune&quot;)<br>}</pre><p>You can modify the stations of train TR01. And Kotlin does not have a way to create a copy read only list in Train during initialization.</p><h4>Immutability in Java records</h4><p>Records are more versatile and immutability is at its core. You can enforce immutability pattern in Java for the same train class as</p><pre>public record Train(String name, List&lt;String&gt; stations) {<br>    public Train(String name, List&lt;String&gt; stations) {<br>        this.name = name;<br>        this.stations = List.copyOf(stations);<br>    }<br>}</pre><p>So when you initialise a Train instance with a name and list of stations you cannot modify the stations of the train.</p><h4>How to enforce Immutability in Kotlin ?</h4><p>Currently there are two ways of enforcing immutability.</p><p>(updated 20 Nov 2023 based on feedback) Firstly you can write your data class with a private param <em>_station</em> to primary constructor and declare/initialize station field inside the body.</p><pre><br>data class Train(val name: String, private val _stations: List&lt;String&gt;) {<br>    val stations = _stations.toList()<br>}<br><br></pre><p>The second way I see right now to write a deep immutable class is not a data class at all. You can do it in a Kotlin class as</p><pre>class Train(val name: String, stations: List&lt;String&gt;) {<br>    val stations = stations.toList()<br>}</pre><p>And this then brings you to classes without any synthetic equals() and hashCode().</p><h4><strong>Conclusion</strong></h4><p>Even though Kotlin data classes are powerful and versatile than Java records because of the copy constructors and default values but they enforce shallow immutability to the class fields.</p><p>Do comment if you like this article or if I missed an approach while writing it and I would update it promptly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=464d7bb9a11c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Micrometer Prometheus metrics with Jersey REST]]></title>
            <link>https://medium.com/@malhotra.vivek/micrometer-prometheus-metrics-with-jersey-rest-99413f4a1152?source=rss-cac2c9397ec8------2</link>
            <guid isPermaLink="false">https://medium.com/p/99413f4a1152</guid>
            <category><![CDATA[jetty]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[jersey]]></category>
            <category><![CDATA[micrometer]]></category>
            <category><![CDATA[prometheus]]></category>
            <dc:creator><![CDATA[Vivek Malhotra]]></dc:creator>
            <pubDate>Sat, 05 Nov 2022 23:10:49 GMT</pubDate>
            <atom:updated>2022-11-05T23:10:49.177Z</atom:updated>
            <content:encoded><![CDATA[<h3>Background</h3><p>Recently we implemented prometheus in one of our microservices. This microservices had a few REST resources and database operations. The application is writen using jersey REST framework. We decided to use micrometer framework to expose prometheus metrics in our app.</p><p>However when I looked around for a good tutorial to implement this there were none around so this led me to write this article.</p><h3>Libraries and dependencies</h3><p>This article assumes your app is written with:</p><ul><li><a href="https://eclipse-ee4j.github.io/jersey.github.io/documentation/latest/jaxrs-resources.html">Jersey</a> lib version 2.35 for REST resources</li><li>Java 11 or higher</li></ul><p>Also to expose prometheus metrics we are using <a href="https://github.com/micrometer-metrics/micrometer">Micrometer</a> version 1.9.2. We also assume you are not using Spring framework and working with injecting dependencies by code setup with an embedded webserver like Jetty 10.0.</p><h3>Initializing a MeterRegistry</h3><p>In your main class initialize a MeterRegistry for prometheus metrics. You can also provide it a PrometheusConfig instance which sets step size for timed calculations or use PrometheusConfig.DEFAULT instead :</p><pre>PrometheusMeterRegistry meterRegistry = <strong>new </strong>PrometheusMeterRegistry(PrometheusConfig.<strong><em>DEFAULT</em></strong>);<br>meterRegistry.config().commonTags(<strong>&quot;app&quot;</strong>, &quot;my-app&quot;);<br>meterRegistry.config().meterFilter(<strong>new </strong>PrefixFilter(&quot;my-app&quot;));</pre><p>This will set a common tag <em>app=my-app</em> to all your metrics for this app. Also all metric names will have my-app appended to them. This makes it easy to search for them later in a metrics viewer like grafana.</p><p>This meterRegistry can now be passed around when you setup your application components like services, database layer, components to build different metrics like Gauge, Counters, Timers etc.</p><h3>Setting up metrics around REST resource</h3><p>To setup metrics around your rest resource you can init a <em>MetricsApplicationEventListener</em> from micrometer-core lib which is an implementation of jersey ApplicationEventListener. This will listen to RequestEvents and update metrics.</p><p>You can read further about its internal working in MetricsRequestEventListener class. The code will look like this:</p><pre>ResourceConfig resourceConfig = <strong>new </strong>ResourceConfig()<br>.register(<strong>new Rest</strong>Resource())<br>.register(<strong>new </strong>MetricsApplicationEventListener(<strong>meterRegistry</strong>, <strong>new </strong>DefaultJerseyTagsProvider(), <strong>&quot;http.server.requests&quot;</strong>, <strong>true</strong>))</pre><pre>ServletContainer servletContainer = <strong>new </strong>ServletContainer(resourceConfig);<br>ServletHolder servletHolder = <strong>new </strong>ServletHolder(servletContainer);<br><br>servletContextHandler.addServlet(servletHolder, &quot;<strong><em>/api/*&quot;</em></strong>);</pre><p>we provide same prometheus <em>meterRegistry</em> that was created earlier. Also we used <em>DefaultJerseyTagsProvider</em> which converts the jersey rest anotations into tags on your metrics. <strong>“http.server.requests” </strong>is default metrics if one is not provided as an anotation on your rest resource. ResourceConfig is set into a jetty <em>ServletContextHandler.</em></p><h4>REST Resources</h4><p>A jersey REST resource will need a micrometer <em>Timed</em> annotations on it. For instance:</p><pre>@Timed(value = &quot;<strong><em>http.server.api.user.byid&quot;</em></strong>, percentiles = {MetricsService.<strong><em>P_95</em></strong>, MetricsService.<strong><em>P_50</em></strong>})<br>@GET<br>@Path(<strong>&quot;/api/user/{userId}&quot;</strong>)<br><strong>public </strong>Response getPlayerByUserId(@PathParam(<strong>&quot;userId&quot;</strong>) long userId) {<br>...</pre><p>This will create multiple Timer metrics with this name and common tags</p><blockquote><strong>my-app_http_server_api_user_byid_seconds{method=”POST”, uri=”api/user/{userId}”}</strong></blockquote><p>There will be some more tags like quantile=”0.95&quot; and quantile=”0.50&quot; since we provide these percentiles in Timed annotation. There will be tags like status=”200” for success response and status=”4xx/5xx” for error responses.</p><p>It will also create a counter with same name and an extra <em>_count</em> suffix.</p><blockquote><strong>my-app_http_server_api_user_byid_seconds_count</strong></blockquote><h3>Expose prometheus metrics</h3><p>Now we come to the last bit of this puzzle. How to expose prometheus metrics as REST resource so that it can be scrapped and pushed to a storage so that it can be queries later. This is straight forward in a jetty embedded server using <em>ServletContextHandler </em>and setting a<em> ServletHolder </em>with<em> </em><a href="https://prometheus.github.io/client_java/io/prometheus/client/exporter/MetricsServlet.html"><em>MetricsServlet</em></a> from prometheus lib.</p><pre>servletContextHandler.addServlet(<br>    <strong>new </strong>ServletHolder(<strong>new </strong>MetricsServlet(((PrometheusMeterRegistry) <strong>meterRegistry</strong>).getPrometheusRegistry())),<br>    <strong>&quot;/metrics&quot;<br></strong>);</pre><p>This exposes your prometheus metrics to the endpoint. The port is what you configured for this <em>ServletContextHandler.</em></p><blockquote><a href="http://localhost:8082/metrics">http://localhost:8082/metrics</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99413f4a1152" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Async scheduled job in Kotlin]]></title>
            <link>https://medium.com/@malhotra.vivek/async-scheduled-job-in-kotlin-325ddcfcbe64?source=rss-cac2c9397ec8------2</link>
            <guid isPermaLink="false">https://medium.com/p/325ddcfcbe64</guid>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[scheduled-jobs]]></category>
            <category><![CDATA[coroutinescope]]></category>
            <category><![CDATA[scheduled-tasks]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Vivek Malhotra]]></dc:creator>
            <pubDate>Thu, 23 Dec 2021 23:54:36 GMT</pubDate>
            <atom:updated>2021-12-23T23:54:36.857Z</atom:updated>
            <content:encoded><![CDATA[<h3>Background</h3><p>So I have been writing an applications at my current workplace in Kotlin for a year now. We are also using coroutines for running non-blocking and asynch code-blocks. In certain flows we have a requirement to run a block of logic at a fixed rate in future. It could be to update a cache store with data from a rest api specially if we cannot have the updates pushed to us via some messages or events.</p><h3>How we did it in Java</h3><p>So in plain Java executer-service jargon we do it as:</p><pre>ScheduledExecutorService executorService = Executors .newSingleThreadScheduledExecutor();<br>Future&lt;String&gt; result = executorService.scheduleAtFixedRate(runnableTask, 500, 1000, TimeUnit.MILLISECONDS);</pre><p>Besides this we had prior experience writing applications with Java + vertx (another non-blocking framework). And in vertx we had a nice way to achieve this. For instance to run a code-block every 1 sec:</p><pre>vertx.setPeriodic(1000, id -&gt; {<br>  // the id is a unique execution id for this handler<br>  System.out.println(&quot;Do something interesting every-time&quot;);<br>});</pre><h3>and Kotlin?</h3><p>So in kotlin and coroutines we do not have any utility functions to schedule a job at fixed intervals. We wanted to leverage kotlin coroutines’s light-weight threading model and not use old-school Java executor-service(though it works as well).</p><p>In kotlin you basically have the concept of extension function and since jobs are run in a CoroutineScope it meant we extend it. We also wanted a feature of initialDelay like Java executor-service has in addition to the fixed period at which a code-block will execute. This is how our version of utility function looks like in kotlin.</p><pre><strong>fun </strong>CoroutineScope.scheduleAtFixedRateAsync(<br>    initialDelay: Duration, period: Duration, action: <strong>suspend </strong>() -&gt; Unit<br>): Job = <em>launch </em><strong>{<br>    </strong>delay(initialDelay)<br>    <strong>while </strong>(<em>isActive</em>) {<br>        action()<br>        delay(period)<br>    }<br><strong>}</strong></pre><p>basically we use <em>launch</em> directive to launch an asych job. Then we <em>delay()</em> or suspend the execution for <em>initial delay</em>. And then keep executing our <em>action</em> block every fixed delay defined by <em>period</em>. You can easily cancel this Job by calling <em>cancel()</em> function on it or the parent scope.</p><p>If you have some other way to solve this problem in kotlin do let us know in the comments below. You can also follow me to get notified of new articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=325ddcfcbe64" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating a Microservice from java 11 to 17 — Part 1]]></title>
            <link>https://medium.com/@malhotra.vivek/migrating-a-microservice-from-java-11-to-17-part-1-5cf773e19e0b?source=rss-cac2c9397ec8------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cf773e19e0b</guid>
            <category><![CDATA[java11]]></category>
            <category><![CDATA[java17]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[jdk]]></category>
            <category><![CDATA[migration]]></category>
            <dc:creator><![CDATA[Vivek Malhotra]]></dc:creator>
            <pubDate>Mon, 27 Sep 2021 19:33:59 GMT</pubDate>
            <atom:updated>2021-09-27T19:33:59.117Z</atom:updated>
            <content:encoded><![CDATA[<h3>Migrating a Microservice from java 11 to 17 — Part 1</h3><p>JDK 17 is finally available as on 14 September 2021. It is latest LTS version of Java after ver. 11 which was made available in September 2018.</p><p>In my company all of our applications/microservices are on JDK 11. Since JDK 17 is general available we thought of let us migrate our applications. A point to note here is our microservices should run on Java 17 runtime out of the box because of backward compatibility.</p><p>However once we build our microservices on JDK 17 we have the power to utilise language features in Java 17 which have been introduced since Java 11. You can read the JEPs since Java 11 <a href="https://openjdk.java.net/projects/jdk/17/jeps-since-jdk-11">here</a>.</p><p>Tech-stack of a generic Microservices looks something like this:</p><ul><li>Java 11</li><li>Maven 3 for dependency management and building project</li><li>JUnit 5 for unit tests</li><li>Spock-Groovy for integration tests</li></ul><p>Before we begin with migrating an application from JDK 11 to 17 we first see how our project’s parent pom looks like.</p><pre>&lt;properties&gt;<br>    &lt;maven.compiler.source&gt;11&lt;/maven.compiler.source&gt;<br>    &lt;maven.compiler.target&gt;11&lt;/maven.compiler.target&gt;<br>.<br>.<br>&lt;/properties&gt;</pre><pre>&lt;build<br>    &lt;pluginManagement&gt;<br>        &lt;plugins&gt;<br>            &lt;plugin&gt;<br>                &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;<br>                &lt;version&gt;3.8.0&lt;/version&gt;<br>            &lt;/plugin&gt;<br>.<br>.<br>.</pre><p>We also use gmavenplus-plugin to compile groovy for spock based integration-tests.</p><pre>&lt;plugin&gt;<br>    &lt;groupId&gt;org.codehaus.gmavenplus&lt;/groupId&gt;<br>    &lt;artifactId&gt;gmavenplus-plugin&lt;/artifactId&gt;<br>    &lt;version&gt;1.9.0&lt;/version&gt;<br>    &lt;executions&gt;<br>        &lt;execution&gt;<br>            &lt;goals&gt;<br>                &lt;goal&gt;compileTests&lt;/goal&gt;<br>            &lt;/goals&gt;<br>        &lt;/execution&gt;<br>    &lt;/executions&gt;<br>    &lt;configuration&gt;<br>        &lt;targetBytecode&gt;11&lt;/targetBytecode&gt;<br>    &lt;/configuration&gt;<br>&lt;/plugin&gt;</pre><p>Firstly, we have to install JDK 17 our developer machine. You can download your favourite JDK 17 binaries from i.e Oracle, OpenJDK or other third party builds. I have a macbook m1 and installed JDK 17 from Oracle using the following <a href="https://www.oracle.com/java/technologies/downloads/#jdk17-mac">link</a>.</p><p>Now, let us update maven-compiler-plugin to 3.8.1 and change the values of source and target to 17.</p><pre>&lt;properties<br>    &lt;maven.compiler.source&gt;17&lt;/maven.compiler.source&gt;<br>    &lt;maven.compiler.target&gt;17&lt;/maven.compiler.target&gt;<br>.<br>.<br>&lt;/properties&gt;</pre><pre>&lt;build<br>    &lt;pluginManagement&gt;<br>        &lt;plugins&gt;<br>            &lt;plugin&gt;<br>                &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;<br>                &lt;version&gt;3.8.1&lt;/version&gt;<br>            &lt;/plugin&gt;<br>.<br>.<br>.&gt;</pre><p>The other thing to note here is that our target bytecode version for Groovy is 11 as well. However before simply changing it to 17 we lookup documentation of gmavenplus-plugin. You can only specify targetBytecode as 16 on version 1.12.1.</p><p>Update: As on 24th Sept 2021, gmavenplus-plugin has released version 1.13.0 which supports targetBytecode 17.</p><pre>&lt;plugin<br>    &lt;groupId&gt;org.codehaus.gmavenplus&lt;/groupId&gt;<br>    &lt;artifactId&gt;gmavenplus-plugin&lt;/artifactId&gt;<br>    &lt;version&gt;1.13.0&lt;/version&gt;<br>    &lt;executions&gt;<br>        &lt;execution&gt;<br>            &lt;goals&gt;<br>                &lt;goal&gt;compileTests&lt;/goal&gt;<br>            &lt;/goals&gt;<br>        &lt;/execution&gt;<br>    &lt;/executions&gt;<br>    &lt;configuration&gt;<br>        &lt;targetBytecode&gt;17&lt;/targetBytecode&gt;<br>    &lt;/configuration&gt;<br>&lt;/plugin&gt;&gt;</pre><p>Building our project with mvn clean install gave us this error:</p><pre>java.lang.UnsupportedOperationException: PermittedSubclasses requires ASM9<br>	at groovyjarjarasm.asm.ClassVisitor.visitPermittedSubclass(ClassVisitor.java:266)<br>	at groovyjarjarasm.asm.ClassReader.accept(ClassReader.java:683)<br>	at groovyjarjarasm.asm.ClassReader.accept(ClassReader.java:401)<br>	at org.codehaus.groovy.ast.decompiled.AsmDecompiler.parseClass(AsmDecompiler.java:81)<br>	at org.codehaus.groovy.control.ClassNodeResolver.findDecompiled(ClassNodeResolver.java:251)<br>	at org.codehaus.groovy.control.ClassNodeResolver.tryAsLoaderClassOrScript(ClassNodeResolver.java:189)<br>	at org.codehaus.groovy.control.ClassNodeResolver.findClassNode(ClassNodeResolver.java:169)<br>	at org.codehaus.groovy.control.ClassNodeResolver.resolveName(ClassNodeResolver.java:125)<br>	at org.codehaus.groovy.ast.decompiled.AsmReferenceResolver.resolveClassNullable(AsmReferenceResolver.java:57)<br>	at org.codehaus.groovy.ast.decompiled.AsmReferenceResolver.resolveClass(AsmReferenceResolver.java:44)<br>	at org.codehaus.groovy.ast.decompiled.TypeSignatureParser.visitEnd(TypeSignatureParser.java:110)<br>	at groovyjarjarasm.asm.signature.SignatureReader.parseType(SignatureReader.java:206)</pre><p>This points to the issue that groovy 3.0.8 cannot handle PermittedSubclass attributes as detailed here in <a href="https://issues.apache.org/jira/browse/GROOVY-10194">apache jira issue</a>. This was fixed in 3.0.9. To use groovy 3.0.9 we add this dependency to our dependency management.</p><pre>&lt;dependency<br>    &lt;groupId&gt;org.codehaus.groovy&lt;/groupId&gt;<br>    &lt;artifactId&gt;groovy&lt;/artifactId&gt;<br>    &lt;version&gt;3.0.9&lt;/version&gt;<br>    &lt;scope&gt;test&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><p>After adding this, we could successfully build our application. In the next article we will also touch on various Java 17 language semantics that we incorporated into our microservice.</p><p>In Part 2 of this article we will look at language features changes from Java 11 to 17.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cf773e19e0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating your code from Java 11 to 17 — Part 2]]></title>
            <link>https://medium.com/@malhotra.vivek/migrating-your-code-from-java-11-to-17-part-2-fcabbc9cf1f8?source=rss-cac2c9397ec8------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcabbc9cf1f8</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[jdk-17]]></category>
            <category><![CDATA[java11]]></category>
            <category><![CDATA[sealed-classes]]></category>
            <category><![CDATA[java17]]></category>
            <dc:creator><![CDATA[Vivek Malhotra]]></dc:creator>
            <pubDate>Mon, 27 Sep 2021 17:26:58 GMT</pubDate>
            <atom:updated>2021-09-27T17:26:58.954Z</atom:updated>
            <content:encoded><![CDATA[<h3>Migrating your code from Java 11 to 17 — Part 2</h3><p>In my previous article I discussed and outlined steps to migrate a typical microservice in our team from JDK 11 to JDK 17. This approach was simply to build our application with JDK 17 but did not use the latest language semantics in Java 17.</p><p>Java 17 is the LTS release after version 11. Though a lot of the language features were introduced in versions after Java 11, it makes more sense to move to Java 17 with premier support up until September 2026. The JEPs incorporated in Java 17 since 11 are listed on this <a href="https://openjdk.java.net/projects/jdk/17/jeps-since-jdk-11">page</a>.</p><p>Let us look the code changes that we did in our application with what java 17 has to offer.</p><h3>Records</h3><p><a href="https://openjdk.java.net/jeps/395">JEP 395</a>: Records were added to Java 14 as preview and finalised in Java 16. Let us look at a class in our application which was written in Java 11.</p><pre>public class Outcome {<br>    private final long id;<br>    private final long betOfferId;<br>    private final long eventId;<br>    private final Optional&lt;BigDecimal&gt; odds;</pre><pre>    public Outcome(long id, long betOfferId, long eventId,<br>                   Optional&lt;BigDecimal&gt; odds) {<br>        this.id = id;<br>        this.betOfferId = betOfferId;<br>        this.eventId = eventId;<br>        this.odds = Objects.requireNonNull(odds);<br>    }<br></pre><pre>    @Override<br>    public boolean equals(Object o) {<br>        if (this == o) return true;<br>        if (o == null || getClass() != o.getClass()) return false;<br>        Outcome that = (Outcome) o;<br>        return id == that.id &amp;&amp; betOfferId == that.betOfferId &amp;&amp; eventId == that.eventId &amp;&amp; Objects.equals(odds, that.odds);<br>    }<br></pre><pre>    @Override<br>    public int hashCode() {<br>        return Objects.hash(id, betOfferId, eventId, odds);<br>    }<br></pre><pre>    @Override<br>    public String toString() {<br>        return &quot;Outcome{&quot; +<br>                &quot;id=&quot; + id +<br>                &quot;, betOfferId=&quot; + betOfferId +<br>                &quot;, eventId=&quot; + eventId +<br>                &quot;, odds=&quot; + odds +<br>                &#39;}&#39;;<br>    }<br>}</pre><p>All this boiler plate code can be written as a record class in Java 17.</p><pre>public record Outcome(long id,<br>                      long betOfferId,<br>                      long eventId,<br>                      Optional&lt;BigDecimal&gt; odds) {<br>    public Outcome {<br>        Objects.requireNonNull(odds);<br>    }<br>}</pre><p>Notice that since Java objects are nullable we still have to redefined canonical constructor to enforce null-check on the optional odds field. However able to not override all methods toString(), hashCode() and equals() is a welcome step.</p><h3>Switch expressions</h3><p><a href="https://openjdk.java.net/jeps/361">JEP 361</a>: Switch expressions were first introduced as preview in Java 12 and 13 and finally released in version 14. You can convert a simple switch statement like this:</p><pre>static &lt;T&gt; List&lt;T&gt; tail(List&lt;T&gt; list) {<br>    switch (list.size()) {<br>        case 0:<br>           throw new IllegalArgumentException(&quot;tail on empty list&quot;);<br>        case 1:<br>            return List.of();<br>        default:<br>            return list.subList(1, list.size());<br>    }<br>}</pre><p>into switch expressions:</p><pre>static &lt;T&gt; List&lt;T&gt; tail(List&lt;T&gt; list) {<br>    return switch (list.size()) {<br>        case 0 -&gt; throw new IllegalArgumentException(&quot;tail on empty list&quot;);<br>        case 1 -&gt; List.of();<br>        default -&gt; list.subList(1, list.size());<br>    };<br>}</pre><p>Some of the advantages of switch expressions are; Avoid multiple return statements in switch case. Group multiple cases into one expression like.</p><pre>case CAR, LORRY -&gt; &quot;something&quot;;</pre><p>You also observe that switch expressions avoid using <em>break;</em> statement between cases.</p><h3>Sealed classes</h3><p><a href="https://openjdk.java.net/jeps/409">JEP 409</a>: Sealed classes were delivered as preview in java 15 and finalised in version 17. Sealed classes can be used in scenarios where we only want a fixed sub-types or implementations of a class or interface. For instance in our domain we have an RuntimeException called WebApplicationException and we know that it can have fixed subtypes HttpClientException and InternalServerException. This can be represented as:</p><pre>sealed class WebApplicationException extends RuntimeException<br>        permits HttpClientException, InternalServerException {<br>}</pre><pre>final class HttpClientException extends WebApplicationException {<br>}</pre><pre>final class InternalServerException extends WebApplicationException {<br>}</pre><p>The subclasses of a sealed class can be either a final, sealed or non-sealed. Difference between a final and non-sealed subclass is whether you want it to be subsequently inherited or not.</p><h3>InstanceOf pattern matching</h3><p>This is one of my favourite language features moving from java 11 to 17. Basically after an instanceOf check you can skip Casting the variable and simply use it as an instance of the target type.</p><pre>public Optional&lt;Long&gt; getEventId(Object obj) {<br>    if (obj instanceof Outcome) {<br>        return of(((Outcome)obj).eventId());<br>    }<br>    return empty();<br>}</pre><p>becomes</p><pre>public Optional&lt;Long&gt; getEventId(Object obj) {<br>    if (obj instanceof Outcome outcome) {<br>        return of(outcome.eventId());<br>    }<br>    return empty();<br>}</pre><h3>Text blocks</h3><p><a href="https://openjdk.java.net/jeps/378">JEP 378</a>: Text blocks are good in projects with long and multiline string literals. One of our application uses jdbi and sql queries. so basically:</p><pre>private static final String SET_DISABLED_SQL =<br>        &quot;UPDATE outcome SET &quot; +<br>        &quot;inactive = :inactive &quot; +<br>        &quot;WHERE outcome_id = :outcome_id&quot;;</pre><p>becomes</p><pre>private static final String SET_DISABLED_SQL =<br>        &quot;&quot;&quot;<br>            UPDATE outcome SET<br>            inactive = :inactive<br>            WHERE outcome_id = :outcome_id<br>        &quot;&quot;&quot;;</pre><h3>Miscellaneous</h3><p>Last section of our article will talk about some small language improvements.</p><p># you can use Stream.toList() instead of Stream.collect(toList()) — one thing to note here is that collection returned by Stream.toList() is unmodifiable.</p><p># you can call String.formatted() on instance of String and use it as a short-hand for static method String.format()</p><p>I will keep updating this article with more language changes we will come across.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcabbc9cf1f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>