<?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 Orkun Akile on Medium]]></title>
        <description><![CDATA[Stories by Orkun Akile on Medium]]></description>
        <link>https://medium.com/@deependdev?source=rss-75019b2ce370------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*If08B6qSIaPV3xVw6S6sxQ.jpeg</url>
            <title>Stories by Orkun Akile on Medium</title>
            <link>https://medium.com/@deependdev?source=rss-75019b2ce370------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 11:27:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@deependdev/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[Build-Time Augmentation Maturity of Java Frameworks: Part 1 — Architectural Landscape]]></title>
            <link>https://levelup.gitconnected.com/build-time-augmentation-maturity-of-java-frameworks-part-1-architectural-landscape-39295256955d?source=rss-75019b2ce370------2</link>
            <guid isPermaLink="false">https://medium.com/p/39295256955d</guid>
            <category><![CDATA[build-time-augmentation]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[quarkus]]></category>
            <category><![CDATA[micronaut]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Orkun Akile]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 21:21:58 GMT</pubDate>
            <atom:updated>2026-10-23T06:44:17.435Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JTJHlQ_3AlEs6nlBbLLwiw.png" /><figcaption>Forged Before Motion</figcaption></figure><p>Most discussions around Java AOT (Ahead-of-Time) enhancements focus on compiler-level optimizations that translate bytecode into native machine executables, such as building a GraalVM Native Image. Equally important is <strong>framework-level build-time augmentation</strong> — how frameworks generate code, precompute state, and eliminate reflection before the application ever boots. This article of a two-part series examines the build-time augmentation capabilities of Java frameworks, by comparing Spring Boot (AOT), Micronaut, and Quarkus across their build phases, metadata access mechanisms, reflection elimination, and custom extension models , also looking at how they diverge so sharply across their module ecosystems.</p><p>Frameworks essentially enhance application behavior by providing ready-made infrastructure within a clearly defined boundary. In the Java ecosystem, major enterprise frameworks historically performed these enhancements almost exclusively at runtime. The Spring Framework, for instance, pioneered its programming model using dynamic runtime mechanisms such as handling configuration loading, dependency injection, dynamic proxy generation, and behavioral interception at runtime. However, relying on runtime introspection incurs significant overhead during application startup and execution for classpath scanning, metadata resolution, and dynamic wiring. Fundamentally, this approach is suboptimal: why repeat the same resolution and wiring work on every startup when it can be computed once at build time? This overhead became a critical bottleneck in the era of elastic cloud-native deployments and serverless (FaaS/Lambda) workloads. To solve this directly, frameworks like Micronaut and Quarkus were born, and Spring has recently moved to catch up by integrating its own build-time processing engine.</p><p>Currently, Java frameworks vary widely in the maturity and depth of their build-time augmentation capabilities. In this article, I classify their build-time maturity into three distinct tiers:</p><ul><li><strong>Specialized Compile-Time Support:</strong> Targeted libraries and tools that solve specific, isolated concerns at compile time, such as Dagger, AspectJ, MapStruct, Lombok, and Immutables.</li><li><strong>Hybrid Frameworks with Build-Time Integration:</strong> Traditional enterprise frameworks that have layered build-time processing on top of existing runtime architectures, such as Spring Boot (with Spring AOT) and Helidon 4 (Declarative). While their core containers support build-time wiring, deep behavioral code generation remains limited across their broader module ecosystems.</li><li><strong>Native Build-Time Platforms:</strong> Comprehensive platforms engineered from the ground up around build-time augmentation and supported by broad, reflection-free ecosystems. Even within this tier, their architectures and extension models diverge into two distinct subcategories:<strong> <br>— Compiler-Based Platforms (Micronaut):</strong> Relies primarily on standard compiler hooks to inspect the Abstract Syntax Tree and generate code during compilation.<br>— <strong>Orchestrated Metaprogramming Platforms (Quarkus):</strong> Provides a unified, post-compile metaprogramming pipeline that indexes global bytecode and orchestrates build steps across the entire classpath.</li></ul><p>In the next section, I examine and compare Spring Boot, Micronaut, and Quarkus from a high-level architectural perspective.</p><p><strong>Framework Architectures</strong></p><p><strong>Spring Boot: Hybrid Framework with Build-Time Integration</strong></p><p>Introduced in Spring Boot 3 and expanded in Boot 4, Spring AOT retrofits a traditional runtime-first architecture for native-image compatibility and build-time enhancements.</p><p><strong>Build Phase:</strong> Rather than hooking into the compiler, Spring runs its augmentation at the post-compile stage (<em>process-aot </em>goal) via <em>BeanRegistrationAotProcessor</em> and <em>BeanFactoryInitializationAotProcessor</em>. It boots a simulated <em>ApplicationContext</em> in memory to inspect <em>BeanDefinition</em> models using live JVM reflection and <em>ASM</em> (<em>MetadataReader</em>), then emits source and bytecode via an internal <em>JavaPoet</em> fork (<em>org.springframework.javapoet</em>) and <em>CGLIB/ASM</em>. Because its generator is strictly additive, emitting new classes and proxies alongside the existing classpath, it cannot modify third-party JAR bytecode.</p><p><strong>Runtime Phase:</strong> Support for precomputing init data is limited to pre-resolving the bean dependency graph; configuration files (<em>application.yml</em>), internal registries, and routing maps are still parsed and populated dynamically at startup. Because it bridges a dynamic runtime, Spring achieves partial elimination of reflection and reflection hints generation, i.e. replacing reflection for core bean wiring while emitting GraalVM RuntimeHints metadata (<em>reflect-config.json</em>, proxy definitions) so the rest of the framework can continue executing reflectively at runtime.</p><p><strong>Ecosystem &amp; Extensibility:</strong> Consequently, ecosystem support for behavioral code generation is narrow: outside of core DI wiring and proxy generation, only Spring Data performs deep behavioral generation (creating concrete <em>*__AotRepository</em> classes, pre-parsed queries, and bytecode property accessors), while Web, Messaging, and Cloud rely primarily on reflection hints. Developers have custom extension support via processor hooks registered in <em>META-INF/spring/aot.factories</em>, though these processors execute sequentially on the <em>BeanFactory</em> without an inter-module dependency graph.</p><p><strong>Micronaut: Build-Time Platform — Compiler-Bounded</strong></p><p>Designed from the ground up as a reflection-free platform, Micronaut shifts framework overhead directly into the standard compilation phase.</p><p><strong>Build Phase:</strong> Micronaut runs its primary augmentation at compile-time via <em>APT/KSP</em> (Annotation Processing Tool/Kotlin Symbolic Processing), hooking into the compiler through its language-neutral <em>TypeElementVisitor</em> SPI, supplemented by optional post-compile optimizations via <em>AOTCodeGenerator</em> (<em>micronaut-aot</em>). Instead of loading classes into the JVM, it accesses class metadata directly from the compiler’s in-memory Abstract Syntax Tree (AST) and generates Java/Kotlin sources or bytecode using <em>Micronaut SourceGen</em> and ASM. Because it operates through compiler visitors on the current compilation unit, it cannot modify third-party code inside pre-compiled dependency JARs, relying instead on generated wrapper beans and adapters.</p><p><strong>Runtime Phase:</strong> At startup, Micronaut benefits from precomputing init data during the build: it constructs static bean and annotation registries, pre-computes routing tables, and uses <em>micronaut-aot</em> to convert YAML/Properties files into static Java configuration maps. This compiler-native architecture achieves full elimination of reflection at runtime across the framework, utilizing switch-based property accessors (<em>@Introspected</em>) and static executable method dispatchers instead of dynamic introspection.</p><p><strong>Ecosystem &amp; Extensibility:</strong> Ecosystem support spans most major modules — including DI, AOP, Micronaut Data (pre-computing repository queries), Serialization (micronaut-serde generating static serializers), Web routing, Messaging, and Cloud. Custom extension support is exposed through <em>APT/KSP TypeElementVisitor</em> hooks (and <em>AOTCodeGenerator</em> plugins), offering a fast, standards-based extension mechanism that remains bounded by the compiler lifecycle rather than an orchestrated multi-step DAG.</p><p><strong>Quarkus: Build-Time Platform — Orchestrated Metaprogramming</strong></p><p>Quarkus operates as a holistic build-time metaprogramming platform that splits every module into deployment (build-time) and runtime components.</p><p><strong>Build Phase:</strong> Quarkus executes its augmentation during the post-compile packaging phase inside a dedicated Maven/Gradle build engine, where extensions hook in via <em>@BuildStep</em> methods producing and consuming <em>@BuildItem</em> objects. To avoid the limitations of both live classloading and source-bound <em>APT</em>, Quarkus accesses class metadata globally across the application and all dependency JARs using <em>Jandex</em>, an offline bytecode indexer. It then synthesizes raw <em>.class</em> bytecode directly using <em>Gizmo</em>, and uniquely can modify third-party code by directly patching and transforming raw bytecode inside external dependency JARs before packaging.</p><p><strong>Runtime Phase:</strong> Quarkus provides the most advanced support for precomputing init data: using <em>@Recorder</em> templates, extensions execute framework initialization logic during the build and serialize the resulting populated registries, routing maps, persistence metamodels, and configuration objects directly into startup bytecode instructions. Paired with generated bytecode accessors, proxies, and invocation handlers, Quarkus achieves full elimination of reflection at runtime, allowing the application to bypass traditional bootstrap sequences entirely.</p><p><strong>Ecosystem &amp; Extensibility:</strong> This capability enables comprehensive ecosystem support across both native modules (ArC DI, RESTEasy Reactive) and complex, reflection-heavy third-party libraries (like Hibernate ORM, Kafka, and Camel), which are re-engineered at build time to boot instantly. It is backed by an extensive modular extension system where custom build steps interact across extensions through a reactive Directed Acyclic Graph (DAG).</p><h4>Overview</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3287c9ba357a7ecc865391d075ddeb71/href">https://medium.com/media/3287c9ba357a7ecc865391d075ddeb71/href</a></iframe><p><strong>Conclusion</strong></p><p>In this article, I categorized the build-time augmentation maturity of modern Java frameworks, driven by the push for runtime efficiency in scalable, cloud-native workloads. By examining their underlying architectures and ecosystem coverage, a clear divide emerges. Spring provides a hybrid architectural model, offering build-time wiring in its core container alongside limited behavioral code generation across its broader ecosystem. Conversely, Micronaut and Quarkus were designed from the ground up as native build-time platforms with broad ecosystem support, Micronaut achieving this through standard compiler hooks, and Quarkus extending it into a holistic bytecode metaprogramming model in a more advanced way. In my view, Micronaut and Quarkus currently offer a stronger architectural outlook for cloud-native efficiency than Spring. While Spring has clearly demonstrated its commitment to moving in this direction, it still has a significant way to go across its portfolio.</p><p>In the second part of this series, I will demonstrate how to build a custom framework extension in practice, harnessing the build-time augmentation capabilities of each of these three frameworks.</p><p><strong>Resources</strong></p><ul><li><a href="https://docs.spring.io/spring-framework/reference/core/aot.html">Ahead of Time Optimizations :: Spring Framework</a></li><li><a href="https://micronaut.io/2021/12/20/micronaut-aot-build-time-optimizations-for-micronaut-applications/">Micronaut AOT — Build-Time Optimizations for Micronaut Applications</a></li><li><a href="https://quarkus.io/guides/writing-extensions/">Writing your own extension — Quarkus</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39295256955d" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/build-time-augmentation-maturity-of-java-frameworks-part-1-architectural-landscape-39295256955d">Build-Time Augmentation Maturity of Java Frameworks: Part 1 — Architectural Landscape</a> was originally published in <a href="https://levelup.gitconnected.com">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reactive STOMP Messaging Extension for Quarkus WebSockets]]></title>
            <link>https://medium.com/javarevisited/reactive-stomp-messaging-extension-for-quarkus-websockets-19f016268f32?source=rss-75019b2ce370------2</link>
            <guid isPermaLink="false">https://medium.com/p/19f016268f32</guid>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[messaging]]></category>
            <category><![CDATA[quarkus]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[stomp]]></category>
            <dc:creator><![CDATA[Orkun Akile]]></dc:creator>
            <pubDate>Tue, 02 Sep 2025 07:30:41 GMT</pubDate>
            <atom:updated>2025-09-04T09:14:27.666Z</atom:updated>
            <content:encoded><![CDATA[<p>STOMP (Simple Text Oriented Messaging Protocol) is a lightweight protocol for messaging with brokers (see <a href="https://stomp.github.io/stomp-specification-1.2.html">STOMP specification</a>). It is especially suitable for client-side applications having relatively light messaging requirements to interact with server side. Front-end web applications communicating via WebSockets would be a good particular use case for that. I implemented a reactive and scalable STOMP messaging extension — reactive-stomp-ws — for Websockets in Quarkus framework (Github <a href="https://github.com/deepend0/reactive-stomp-ws">link</a>).</p><h3>Motivation</h3><p>Client-side applications communicate with server-side over limited WebSocket connections for a variety of concerns. Therefore enabling a publish-subscribe communication semantics between those parties will be quite beneficial. In addition, some client-side applications might need messaging with other clients which typically requires a message broker. However, direct access to a broker from client side is undesirable for security, integrity reasons and server-side logic to be executed. Also in this case, publish-subscribe communication with server-side will be useful, in that messaging requirements can be mapped directly. Server-side application can even act as a mediator with some custom logic between client and message broker. For these reasons having a back-end with STOMP server capabilities is envisioned to be an enabler.</p><p>In Java ecosystem, Spring Framework already provides such a capability for Websockets (see <a href="https://spring.io/guides/gs/messaging-stomp-websocket">this</a> guide). However, it is not built to support reactive workflows. At the time, the Quarkus ecosystem lacked a similar back-end library. Since Quarkus framework provides robust support for library development with its extensions including compile-time processing and reactive programming is supported as a first-class citizen, I createdreactive-stomp-ws library for Quarkus.</p><h3>Features</h3><p>The extension is built using Quarkus extension development framework (see <a href="https://quarkus.io/guides/writing-extensions">here</a>) with compile-time augmentation, so that synthetic classes and beans are created in compile time. It internally works fully reactively and employs Reactive Messaging extension (see <a href="https://smallrye.io/smallrye-reactive-messaging">here</a>). The implementation concepts and details will be described in another blog post.</p><p>For now, let’s review the main features from a user’s perspective.</p><p><strong>STOMP Processing</strong></p><p>The extension acts as a STOMP server hand supports STOMP v1.2 by involving heartbeats, acks. Transactions are not yet supported.</p><p><strong>Message Broker</strong></p><p>Messages sent by a STOMP client to configured inbound destinations are handled by a message broker.</p><ul><li>When reactive-stomp-ws-base package is used, a simple in-memory message broker is activated. It works on a FIFO queue with round-robin fashion. In-memory message broker is useful when only client-server interaction is intended. When messaging among clients is needed, in-memory broker would rather help for testing purpose since it wouldn’t offer such a scalability. Allowed destinations can be configured via reactive-stomp.messaging.broker.regex config parameter.</li><li>However, when a scalable messaging is needed, external message brokers can be used. With this setting, messages received from STOMP will be relayed to external brokers. reactive-stomp-ws-kafka and reactive-stomp-ws-amqp packages support Kafka and AMQP message brokers respectively.</li></ul><p><strong>Message Endpoints</strong></p><p>The extension allows you to define message-driven endpoints by simply annotating methods with <a href="http://twitter.com/MessageEndpoint">@MessageEndpoint</a>. Message-driven endpoints can streamline data flow over web socket instead of a mix of request/response and web socket connection. They can also be considered as intermediary between client and broker, so that security, integrity, custom processing or multiple message routing can be done.</p><p>Messages sent to configured inbound destinations are handled by message endpoints. Allowed destinations can be configured via reactive-stomp.messaging.message-endpoint.regex config parameter.</p><p>Message endpoints can handle incoming messages from a given inboundDestination and optionally publish responses to an outboundDestination.</p><p>Endpoints support:</p><ul><li>Synchronous or reactive return values</li><li>Plain or wrapped payloads</li><li>Dynamic inbound/outbound paths with path parameters (using curly braces{}).</li></ul><p>Below is a set of examples demonstrating the different possibilities:</p><pre>public class SampleMessageEndpoints {<br><br>    // 1. Synchronous response<br>    @MessageEndpoint(inboundDestination = &quot;/messageEndpoint/helloSync&quot;, outboundDestination = &quot;/topic/helloSync&quot;)<br>    public String greetingSync(String name) {<br>        return &quot;Hey &quot; + name;<br>    }<br><br>    // 2. Asynchronous response with Uni<br>    @MessageEndpoint(inboundDestination = &quot;/messageEndpoint/helloAsync&quot;, outboundDestination = &quot;/topic/helloAsync&quot;)<br>    public Uni&lt;String&gt; greetingUni(String name) {<br>        return Uni.createFrom().item(&quot;Hello &quot; + name);<br>    }<br><br>    // 3. Streaming response with Multi<br>    @MessageEndpoint(inboundDestination = &quot;/messageEndpoint/intSeries&quot;, outboundDestination = &quot;/topic/intSeries&quot;)<br>    public Multi&lt;Integer&gt; nextIntegers(Integer value) {<br>        return Multi.createFrom().items(IntStream.range(value + 1, value + 11).boxed());<br>    }<br><br>    // 4. Consuming and producing custom objects<br>    @MessageEndpoint(inboundDestination = &quot;/messageEndpoint/obj&quot;, outboundDestination = &quot;/topic/obj&quot;)<br>    public Uni&lt;SampleObject&gt; objUni(SampleObject sampleObject) {<br>        return Uni.createFrom().item(<br>            new SampleObject(&quot;AA&quot; + sampleObject.getId(), sampleObject.getValue() + 1)<br>        );<br>    }<br><br>    // 5. Explicit outbound destination with MessageEndpointResponse<br>    @MessageEndpoint(inboundDestination = &quot;/messageEndpoint/intValue2&quot;)<br>    public MessageEndpointResponse&lt;Uni&lt;Integer&gt;&gt; intUniMessageEndpointResponse(Integer value) {<br>        return new MessageEndpointResponse&lt;&gt;(<br>            &quot;/topic/intValue2&quot;,<br>            Uni.createFrom().item(value + 1)<br>        );<br>    }<br><br>    // 6. Fully async MessageEndpointResponse wrapped in Uni<br>    @MessageEndpoint(inboundDestination = &quot;/messageEndpoint/intValue3&quot;)<br>    public Uni&lt;MessageEndpointResponse&lt;Uni&lt;Integer&gt;&gt;&gt; intUniMessageEndpointResponseUni(Integer value) {<br>        return Uni.createFrom().item(<br>            new MessageEndpointResponse&lt;&gt;(&quot;/topic/intValue3&quot;, Uni.createFrom().item(value + 1))<br>        );<br>    }<br><br>    // 7. Using inbound path parameters and payload<br>    @MessageEndpoint(<br>        inboundDestination = &quot;/messageEndpoint/{user}/helloAsync2&quot;,<br>        outboundDestination = &quot;/topic/helloAsync2&quot;<br>    )<br>    public Uni&lt;String&gt; greetingUniWithInboundPathParams(@PathParam String user, @Payload String name) {<br>        return Uni.createFrom().item(&quot;Hello &quot; + name + &quot; from &quot; + user);<br>    }<br><br>    // 8. Dynamic outbound destinations using path parameters<br>    @MessageEndpoint(<br>        inboundDestination = &quot;/messageEndpoint/{user}/helloAsync5&quot;,<br>        outboundDestination = &quot;/topic/{user}/helloAsync5/{name}&quot;<br>    )<br>    public Uni&lt;String&gt; greetingUniWithIncomingAndOutgoingPathParam(@PathParam String user, @Payload String name) {<br>        return Uni.createFrom().item(&quot;Hello outgoing &quot; + name + &quot; from &quot; + user);<br>    }<br>}</pre><h3>Configuration</h3><p>The extension can be configured via configuration properties. Here is an example yaml configuration for base package:</p><pre>quarkus:<br>  http:<br>    port: 8080<br>  websockets-next:<br>    server:<br>      propagate-subprotocol-headers: true<br>      supported-subprotocols: v12.stomp,v11.stomp #Enable supported websocket subprotocols<br><br>reactive-stomp:<br>  heartbeat: 1000, 1000 #Stomp heartbeat receive and reply period<br>  messaging:<br>    broker:<br>      regex: /topic.* #Regex pattern for destinations to be handled directly by broker<br>    message-endpoint:<br>      regex: /messageEndpoint.* #Regex pattern for destinations to be handled by message endpoints<br>  stomp:<br>    ackPeriod: 1000 #Stomp ack receiving period</pre><p>Example configuration for Kafka module:</p><pre>kafka:<br>  bootstrap-servers: localhost:9092 #Kafka bootstrap servers<br>  producer:<br>    ...                     #Producer properties<br>  consumer:<br>    ...                     #Consumer properties</pre><p>Example configuration for AMQP module:</p><pre>amqp:<br>  host: localhost<br>  port: 5672<br>  username: user<br>  password: pass</pre><h3>Example Chat Application</h3><p>Here you can see how easy it is to implement a simple front-end chat application using stomp.js with a back-end powered byreactive-stomp-ws. You can find the source code <a href="https://github.com/deepend0/reactive-stomp-ws-examples/tree/main/chat-app">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*AtAtftPBlN4bGv6o6y4nZg.jpeg" /><figcaption>Chat page</figcaption></figure><ul><li>Front-end application first subscribes to the topics for receiving the active users, joined users and disconnected users.</li><li>Then it sends a connection request to the server and those subscriptions will be activated.</li><li>When a user wants to have a chat with another user and there is not an existing one, a channel creation request is sent. In turn a channel id is provided to both parties and those parties subscribe to the created channel so that they can start chatting.</li></ul><p>Javascript part on the front-end related to STOMP messaging:</p><pre>&lt;script&gt;<br>    let stompClient = null;<br>    let username = null;<br>    let channels = {};     // channelId -&gt; {users, messages}<br>    let activeChannel = null;<br>    let pendingUser = null;<br><br>    function connectWebSocket() {<br>      stompClient = new StompJs.Client({<br>        brokerURL: &quot;ws://localhost:8080/ws/stomp&quot;, // use wss:// in production<br>        reconnectDelay: 5000,                      // auto reconnect<br>        heartbeatIncoming: 10000,                  // expect server heartbeats every 10s<br>        heartbeatOutgoing: 10000,                  // send heartbeats every 10s<br>        debug: () =&gt; {}                            // silence logs<br>      });<br><br>      stompClient.onConnect = (frame) =&gt; {<br>        console.log(&quot;Connected: &quot;, frame);<br><br>        // Subscribe to initial user list<br>        stompClient.subscribe(&quot;/topic/user/&quot; + username + &quot;/currentUsers&quot;, (message) =&gt; {<br>          const data = JSON.parse(message.body);<br>          updateUserList(data.users);<br>        });<br><br>        // Subscribe to user events<br>        stompClient.subscribe(&quot;/topic/users/connected&quot;, (message) =&gt; {<br>          const data = JSON.parse(message.body);<br>          addUser(data.user);<br>        });<br><br>        stompClient.subscribe(&quot;/topic/users/disconnected&quot;, (message) =&gt; {<br>          const data = JSON.parse(message.body);<br>          removeUser(data.user);<br>        });<br><br>        // Send connect message<br>        stompClient.publish({<br>          destination: &quot;/endpoint/chat/connect/&quot; + username,<br>          body: JSON.stringify({ user: username, fullName: &quot;User &quot; + username })<br>        });<br><br>        // Subscribe to channel creation notifications<br>        stompClient.subscribe(&quot;/topic/user/&quot; + username + &quot;/channel&quot;, (message) =&gt; {<br>          const data = JSON.parse(message.body);<br>          const { channelId, users } = data;<br>          if (!channels[channelId]) {<br>            channels[channelId] = { users, messages: [] };<br>            subscribeToChannel(channelId);<br>          }<br><br>          if (pendingUser &amp;&amp; users.includes(pendingUser)) {<br>            showChat(channelId);<br>            pendingUser = null;<br>          }<br>        });<br>      };<br><br>      stompClient.onStompError = (frame) =&gt; {<br>        console.error(&quot;Broker error: &quot; + frame.headers[&quot;message&quot;]);<br>        console.error(&quot;Details: &quot; + frame.body);<br>      };<br><br>      stompClient.activate();<br>    }<br><br>    function subscribeToChannel(channelId) {<br>      stompClient.subscribe(&quot;/topic/channel/&quot; + channelId, (message) =&gt; {<br>        const data = JSON.parse(message.body);<br>        addMessage(channelId, data.sender, data.message);<br>      });<br>    }<br><br>    function openChatWith(user) {<br>      let existingChannel = Object.keys(channels).find(cid =&gt; channels[cid].users.includes(user));<br>      if (existingChannel) {<br>        showChat(existingChannel);<br>        return;<br>      }<br>      // Mark as pending → once the channel is created we open it<br>      pendingUser = user;<br>      stompClient.publish({<br>        destination: &quot;/endpoint/chat/create&quot;,<br>        body: JSON.stringify({ users: [username, user] })<br>      });<br>    }<br><br>    function sendMessage(channelId) {<br>      const msg = $(&quot;#msg-&quot; + channelId).val().trim();<br>      if (msg.length === 0) return;<br>      stompClient.publish({<br>        destination: &quot;/endpoint/chat/&quot; + channelId + &quot;/message&quot;,<br>        body: JSON.stringify({<br>          channelId,<br>          sender: username,<br>          message: msg<br>        })<br>      });<br>      $(&quot;#msg-&quot; + channelId).val(&quot;&quot;);<br>    }<br><br>    $(document).ready(function () {<br>      $(&quot;#login&quot;).show();<br><br>      $(&quot;#loginBtn&quot;).click(function () {<br>        username = $(&quot;#username&quot;).val().trim();<br>        if (!username) {<br>          $(&quot;#loginError&quot;).text(&quot;Username required&quot;);<br>          return;<br>        }<br><br>        // REST login<br>        $.ajax({<br>          url: &quot;/user/login&quot;,<br>          method: &quot;POST&quot;,<br>          contentType: &quot;application/json&quot;,<br>          data: JSON.stringify({ user: username }),<br>          success: function () {<br>            $(&quot;#login&quot;).hide();<br>            $(&quot;#chat&quot;).show();<br>            $(&quot;#currentUser&quot;).text(&quot;You: &quot; + username);<br>            connectWebSocket();<br>          },<br>          error: function (xhr) {<br>            $(&quot;#loginError&quot;).text(xhr.responseText || &quot;Login failed&quot;);<br>          }<br>        });<br>      });<br><br>      $(document).on(&quot;click&quot;, &quot;.user&quot;, function () {<br>        const targetUser = $(this).data(&quot;user&quot;);<br>        openChatWith(targetUser);<br>      });<br><br>      // Handle disconnect on close<br>      $(window).on(&quot;beforeunload&quot;, function () {<br>        if (stompClient &amp;&amp; stompClient.active) {<br>          stompClient.publish({<br>            destination: &quot;/endpoint/chat/disconnect/&quot; + username,<br>            body: JSON.stringify({ user: username, fullName: &quot;User &quot; + username})<br>          });<br>          stompClient.deactivate();<br>        }<br>      });<br>    });</pre><p>Message endpoints on back-end side:</p><pre>@ApplicationScoped<br>public class ChatMessageEndpoint {<br>    private static final Logger LOGGER = LoggerFactory.getLogger(ChatMessageEndpoint.class);<br><br>    private final UserService userService;<br>    private final ChatService chatService;<br><br>    public ChatMessageEndpoint(UserService userService, ChatService chatService) {<br>        this.userService = userService;<br>        this.chatService = chatService;<br>    }<br><br>    @MessageEndpoint(inboundDestination = &quot;/endpoint/chat/connect/{user}&quot;)<br>    public Multi&lt;MessageEndpointResponse&lt;?&gt;&gt; connect(@PathParam String user, UserDto userDto) {<br>        Set&lt;String&gt; currentUsers = userService.getCurrentUsers();<br>        return Multi.createFrom().items(<br>                MessageEndpointResponse.of(&quot;/topic/user/&quot; + user + &quot;/currentUsers&quot;, new UsersDto(currentUsers)),<br>                MessageEndpointResponse.of(&quot;/topic/users/connected&quot;, userDto));<br>    }<br><br>    @MessageEndpoint(inboundDestination = &quot;/endpoint/chat/create&quot;)<br>    public Multi&lt;MessageEndpointResponse&lt;?&gt;&gt; startChatWith(ChannelRequest channelRequest) {<br>        String channelId = chatService.createChannel(Set.of(channelRequest.users()));<br>        ChannelDto channelDto = new ChannelDto(channelId, channelRequest.users());<br>        return Multi.createFrom().items(MessageEndpointResponse.of(&quot;/topic/user/&quot; + channelRequest.users()[0] + &quot;/channel&quot;, channelDto),<br>                MessageEndpointResponse.of(&quot;/topic/user/&quot; + channelRequest.users()[1] + &quot;/channel&quot;, channelDto));<br>    }<br><br>    @MessageEndpoint(inboundDestination = &quot;/endpoint/chat/{channelId}/message&quot;, outboundDestination = &quot;/topic/channel/{channelId}&quot;)<br>    public Uni&lt;MessageDto&gt; sendMessage(MessageDto messageDto) {<br>        if(userService.getCurrentUsers().contains(messageDto.sender())) {<br>            if(messageDto.message().length() &gt; 250) {<br>                return Uni.createFrom().failure(new IllegalArgumentException(&quot;Message too long&quot;));<br>            }<br>            return Uni.createFrom().item(messageDto);<br>        }<br>        return Uni.createFrom().failure(new IllegalArgumentException(&quot;User doesn&#39;t exist&quot;));<br>    }<br><br>    @MessageEndpoint(inboundDestination = &quot;/endpoint/chat/disconnect/{user}&quot;, outboundDestination = &quot;/topic/users/disconnected&quot;)<br>    public Uni&lt;UserDto&gt; disconnect(@PathParam String user, UserDto userDto) {<br>        userService.removeUser(user);<br>        return Uni.createFrom().item(userDto);<br>    }<br>}</pre><p>Back-end config:</p><pre>quarkus:<br>  http:<br>    port: 8080<br>  websockets-next:<br>    server:<br>      propagate-subprotocol-headers: true<br>      supported-subprotocols: v12.stomp,v11.stomp<br><br>reactive-stomp:<br>  heartbeat: 10000, 10000<br>  messaging:<br>    broker:<br>      regex: /topic.*<br>    message-endpoint:<br>      regex: /endpoint.*<br>  stomp:<br>    ackPeriod: 1000</pre><h3>Conclusion</h3><p>The reactive-stomp-ws extension brings <strong>reactive STOMP messaging over WebSockets</strong> to Quarkus.</p><ul><li>It provides STOMP server functionality.</li><li>It integrates with in-memory or external message brokers.</li><li>It offers a clean, annotation-driven model for message endpoints.</li><li>It is designed for scalability, flexibility, and reactive programming.</li></ul><p>Feel free to reach out if you encounter missing features or bugs. In a follow-up post, I will cover the underlying implementation concepts — such as compile-time augmentation, reactive programming, messaging workflows, and async testing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19f016268f32" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/reactive-stomp-messaging-extension-for-quarkus-websockets-19f016268f32">Reactive STOMP Messaging Extension for Quarkus WebSockets</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Best-Effort Kafka and Database Transactions]]></title>
            <link>https://blog.stackademic.com/implementing-best-effort-kafka-and-database-transactions-f448b071cd44?source=rss-75019b2ce370------2</link>
            <guid isPermaLink="false">https://medium.com/p/f448b071cd44</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[aop]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[transactions]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Orkun Akile]]></dc:creator>
            <pubDate>Mon, 18 Sep 2023 19:53:53 GMT</pubDate>
            <atom:updated>2023-11-14T09:05:40.357Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*OnmWXEmT7s6pSld2cI6W6Q.jpeg" /><figcaption>(Photo by David Rule/@davidmrule)</figcaption></figure><p>Distributed transactions involving Kafka and another data source occur in various scenarios. While strong transactional consistency can be attained using 2-Phase-Commit in distributed transactions, not every data system supports it. Even though Kafka supports transactions with Transactions API, it is not possible to apply 2-Phase-Commit with Kafka and another data source since Kafka doesn’t support XA transactions.</p><p>There are various solutions to multi-source write problems including transactional outbox and choreography-based patterns. However, an intuitive solution, best-effort 1-phase-commit transactions are an efficient alternative. Within that, commit phase is done as the last step for all the parties, after business logic is completed successfully. Since business logic errors are expected more frequently than infrastructure errors, this approach should work fine in practice. If any error occurs in business operations all transactions will be rolled back. Or else if one of the commits fails, the remaining ones will be rolled back. So it will require some manual intervention, i.e. inspecting logs and running mitigation scripts.</p><p>Let’s assume that we have an application following a typical consume-process-publish pattern. We read from a Kafka topic, then write into a database and finally publish into another Kafka topic. We are going to implement chained, best-effort transactions. In this article, this approach will be implemented in two ways: using aspect-oriented programming from scratch and using Spring chained transaction support.</p><h4>AOP Implementation</h4><p>We will implement a straightforward chained transaction manager realizing @Transactional annotation using AspectJ. <em>consumeAndPublish</em> represents a consume-process-publish operation, reading Kafka messages, writing into a database and sending into another topic. It is annotated with @Transactional. An AOP aspect will be implemented to process methods with this annotation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47d7087254cb6d53a3a80d86e8fc40d7/href">https://medium.com/media/47d7087254cb6d53a3a80d86e8fc40d7/href</a></iframe><p>ChainedTxManager is a base class for transaction managers. It uses a transaction handler and implements transaction operations, namely begin, commit, rollback and close. When failed, begin operation doesn’t go further and closes resources backward. Commit and rollback operations trigger rollback on following transaction managers only in case of failure.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4de2d24cb7556a1da6e656b2a4fd389b/href">https://medium.com/media/4de2d24cb7556a1da6e656b2a4fd389b/href</a></iframe><p>TxHandler classes are basically adaptors for resources to handle transaction management operations. Transaction handlers are implemented for JDBC, Kafka producer and consumer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2453bc142bb075690b554cd8cc5e6ff5/href">https://medium.com/media/2453bc142bb075690b554cd8cc5e6ff5/href</a></iframe><p>There is no transaction with Kafka consumers since data consumption doesn’t modify the actual data. However, transaction concept can be applied to committing consumer group offsets. Kafka consumer, created with auto offset commit option set false, commits offsets with commit operation. However there is no need to implement begin and rollback operations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc4c64a2a3226c9041e7b1b35291f6fa/href">https://medium.com/media/bc4c64a2a3226c9041e7b1b35291f6fa/href</a></iframe><p>We need to set transactional id in Kafka producer configuration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4de722190e4318ac81c59438dced81bb/href">https://medium.com/media/4de722190e4318ac81c59438dced81bb/href</a></iframe><p>We also need to set ENABLE_AUTO_COMMIT_CONFIG to false to disable Kafka consumer offset auto commit behavior.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e2c57509e2edf8e210cbffbdbe4a376/href">https://medium.com/media/0e2c57509e2edf8e210cbffbdbe4a376/href</a></iframe><p>The AspectJ aspect for chained transaction management is implemented for @Transactional annotation. A pointcut and an around advice are implemented. Around advice first gets chained transaction manager from the context (dependency locator pattern). It executes the business logic when a transaction begins successfully, and commits the transaction when business logic is executed successfully. Otherwise, it rollbacks the transaction.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8571dc178fcbaa8e682ab866e5478f0b/href">https://medium.com/media/8571dc178fcbaa8e682ab866e5478f0b/href</a></iframe><p>Chained transaction manager is created by chaining Jdbc, Kafka consumer and producer transaction managers. Transactions are started and committed in respective order.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a16b554903bc9b956f384a2cd5114914/href">https://medium.com/media/a16b554903bc9b956f384a2cd5114914/href</a></iframe><h4>Spring Implementation</h4><p>Instead of manual implementation, Spring can be used for chained transaction management. Spring supports Kafka transactions and provides a chained transaction manager.</p><p>First we need to define Kafka producer and consumer in application.yaml file. Kafka producer should have transaction-id-prefix property to support transactions. Also consumer offset auto commit should be disabled.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ab2b1f65e5a49307a8aa2cabc39246f/href">https://medium.com/media/6ab2b1f65e5a49307a8aa2cabc39246f/href</a></iframe><p>In application configuration we create a chained kafka transaction manager. Kafka transaction manager is automatically created. We should supply JDBC transaction manager and kafka transaction manager into chained transaction manager.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f06a819fa0356475a186a85405f927b/href">https://medium.com/media/7f06a819fa0356475a186a85405f927b/href</a></iframe><p>Again, we consume data from a topic and write it into database and another Kafka topic. We need to annotate consumer method with @KafkaListener annotation and @Transactional. Chained Kafka transaction manager should be specified in the @Transactional annotation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eac0785b6aa44fcefed461820d8efb9c/href">https://medium.com/media/eac0785b6aa44fcefed461820d8efb9c/href</a></iframe><h4>Conclusion</h4><p>Best-Effort 1-Phase-Commit transactions are a simple yet practically effective way of implementing distributed transactions when 2-phase-commit cannot be implemented. It is a common use case to read data from messaging queue, process it, save it into a database and publish it into another queue. In this article, we implemented that scenario with AOP using AspectJ from scratch as well as Spring’s built-in capabilities. AOP demonstrates underlying mechanics of a transaction manager, whereas Spring provides an elegant out-of-the-box solution.</p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f448b071cd44" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/implementing-best-effort-kafka-and-database-transactions-f448b071cd44">Implementing Best-Effort Kafka and Database Transactions</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[Collection Support Utility for Spring Cache via AOP]]></title>
            <link>https://deependdev.medium.com/collection-support-utility-for-spring-cache-via-aop-49c634cfc98e?source=rss-75019b2ce370------2</link>
            <guid isPermaLink="false">https://medium.com/p/49c634cfc98e</guid>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Orkun Akile]]></dc:creator>
            <pubDate>Mon, 19 Sep 2022 22:02:07 GMT</pubDate>
            <atom:updated>2022-09-19T22:03:43.898Z</atom:updated>
            <content:encoded><![CDATA[<p>Spring Cache abstraction doesn’t support working with collection parameters in an iterative manner. Instead a scalar caching method can be created and a collection parameter can be iterated using that method. However, it may not be convenient for a method to be broken down into scalar caching methods. For instance, data is frequently retrieved in batches from a database or a network. For those cases, creating a scalar cache method doesn’t isolate the code from caching-specific logic and hence is not a good caching abstraction.</p><p><em>FlatCacheable</em> is a Java utility to extend Spring Cache abstraction in order to support caching of collections in a feasible and flexible way. It can be found in this GitHub repository: <a href="https://github.com/deepend0/spring-cache-ext/">https://github.com/deepend0/spring-cache-ext/</a>.</p><p>Basically, it contains three annotations corresponding “flat” variants of Spring caching method annotations:</p><ul><li>@FlatCacheable</li><li>@FlatCachePut</li><li>@FlatCacheEvict</li></ul><p>Functionality underlying those annotations is implemented via aspect-oriented programming. Directly extending Spring cache module was also considered. However, Spring cache module doesn’t seem to be extendable in a neat way with an external involvement. For that, Spring AOP is used to implement.</p><p>“Flat” analogy in naming is preferred due to the fact that both collection parameter and its collection sub-fields are flattened on-the-fly and each element is cached individually. Besides, as an implementation note, flatMap operation in Java Streams has played a central role to flatten collections. Thus, as a representative one of the annotation names, <em>FlatCacheable</em> is selected as the module name as well.</p><h3>Usage</h3><p>First, the context configuration should be imported, caching and AspectJ proxies should be enabled. Then, you can annotate methods with @FlatCacheable, @FlatCachePut or @FlatCacheEvict annotations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f86a47df5c24b5aa21359d2cd763739c/href">https://medium.com/media/f86a47df5c24b5aa21359d2cd763739c/href</a></iframe><p><strong>@FlatCacheable</strong></p><p>@FlatCacheable does the computation via target method and caches the values from collection parameter only for non-existing elements in the cache.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/980e9db89119567be7b4c211f9c65197/href">https://medium.com/media/980e9db89119567be7b4c211f9c65197/href</a></iframe><p>Key and key-value mapping should be specified using hierarchical dotted field notation. Key should contain key parameter name in method signature with “#” sign (mimics SpEL expressions as for syntax) and then should specify sub-field names if any. Key-value mapping should be done via @FieldMapping. Mapping is required to join key and value objects and therefore to create a key-value map. @keyField is the join field on input parameter and @valueFieldis the one on result value. If a key has a single object to be mapped, then cardinality should be @MappingCardinality.SINGLE, otherwise @MappingCardinality.MULTIPLE. Fields are extracted from each element in the respective collection. If no sub-field is specified, key or value object itself is taken. If a sub-field is a collection then each value of it is taken for join.</p><p><strong>@FlatCachePut</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4953dffc44314f0627956694ea493737/href">https://medium.com/media/4953dffc44314f0627956694ea493737/href</a></iframe><p>@FlatCachePutcomputes the value and then caches no matter whether values exist in the cache or not. It has the same set of parameters as those of @FlatCacheable. However, input parameter and key-value mapping are not mandatory. Keys also can be selected from value object. For that #result special parameter marker should be specified (mimics Spring Caching context variable in naming) and then no @FieldMapping is required.</p><p><strong>@FlatCacheEvict</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f980a4d51f97d037c7bc94eeb766ff25/href">https://medium.com/media/f980a4d51f97d037c7bc94eeb766ff25/href</a></iframe><p>@FlatCacheEvict simply evicts values from the cache based on keys. Keys can be selected either from input parameter or returned value. If key is selected from input parameter, parameter name in method prototype should be specified. Otherwise #result marker should be used.</p><h3>Example</h3><p>Assume that we have regions, polygons and scooters for a scooter rental app. Relationship between these entities is one-to-many respectively. Data is stored inside an SQL DB and JPA is used for ORM. Hence Scooter, Polygon and Region entity classes are created. For demonstration purposes, one-to-many relationships bi-directionally implemented in Polygon class keeping both region and scooters inside.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/efdd872955f99cd9a4c0ae56aa98f5e2/href">https://medium.com/media/efdd872955f99cd9a4c0ae56aa98f5e2/href</a></iframe><p>Apart from entities, Spring JPA repository interfaces of Scooter and Region entities are created. Standard Spring caching annotations are used here along with flat caching annotations. Thus we can see the benefit of the collection support clearly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b88f5c569be80ac9ee3d975ca681005/href">https://medium.com/media/8b88f5c569be80ac9ee3d975ca681005/href</a></iframe><p>@Cacheable-annotated methods return value for a scalar method parameter and value is mapped to that key in the cache, no matter if the result is a collection. On the other hand,@FlatCacheable-annotated methods do the caching for each element in collection parameter by mapping input objects and return values. For findByIdsIn method, key field for field mapping is not specified, because join key is the string value’s itself in ids list. @MappingCardinality.SINGLE is the cardinality for that since each key has a single value. As for @findByPolygon_IdIn and @findByPolygonsIn methods, those two only differ in the type of elements in collection parameter. The one for @findByPolygon_IdIn is StringString, and the other one is Polygon. Therefore, key field is empty for the former and id for the latter. Besides, mapping cardinality is @MappingCardinality.MULTIPLE, since each polygon has many polygons inside.</p><p>Methods @findByPolygon_Region_IdIn and @findByPolygon_Region_In are annotated with @FlatCachePut. Parameters have the same semantics as those of @FlatCacheable. Only that, in field mapping, joining through multiple level field hierarchy is demonstrated with value fields being polygon.region.id. Besides that findAll method exemplifies @FlatCachePut usage with #result parameter.</p><p>deleteAllByIdIn method is annotated with @FlatCacheEvict, meaning that values are evicted from the cache for each id value in list parameter.</p><p>RegionRepository has similar methods. However, it depicts key-value mappings from the other way around.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2c712cfa9ba4eb21ff81d8401d97089/href">https://medium.com/media/d2c712cfa9ba4eb21ff81d8401d97089/href</a></iframe><h3>Summary</h3><p>Flat-caching utility provides collection support for Spring caching abstraction. It is implemented using Spring AOP module. A key-value join mechanism is introduced to handle key-value mapping problem. Its effective usage is demonstrated with a JPA application. This module can be also improved to involve key-value mapper functions and object transformations for the future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49c634cfc98e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Compile-Time Dependency Injection with Dagger 2]]></title>
            <link>https://blog.stackademic.com/compile-time-dependency-injection-using-dagger-bddeb51e8242?source=rss-75019b2ce370------2</link>
            <guid isPermaLink="false">https://medium.com/p/bddeb51e8242</guid>
            <category><![CDATA[dagger-2]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Orkun Akile]]></dc:creator>
            <pubDate>Thu, 18 Nov 2021 16:30:10 GMT</pubDate>
            <atom:updated>2023-09-21T01:31:14.574Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tEGt-N6fS5IgeO_2nyMZfw.jpeg" /></figure><p>Dependency injection has been an integral part of many non-trivial applications, generally empowered by frameworks. It promotes decoupling to such an extend that applications are better extensible, maintainable, configurable and testable. It is generally considered only as a run-time facility because of its dynamic capability and convenience. Most popular frameworks like Spring, JEE CDI and Guice are based on run-time dependency injection.</p><p>However, run-time dependency injection brings about overhead in application performance in terms of memory usage and start-up time, due to run-time resolution of dependencies and reliance on reflection. This overhead might be negligible in the realm of monolithic applications, even though it could grow high. Nevertheless it could be significant in microservice and mobile development. For example, cold start-up time is a critical factor for lambda applications on cloud environments where lambda application is run from scratch very frequently. Eliminating this overhead while still benefiting from dependency injection would be ideal.</p><p><strong>What is Compile-Time Dependency Injection</strong></p><p>Dependency injection involves dependency resolution and actual injection steps. Since actual injection step is about constructing objects, it must be done in run-time. But dependency resolution can be accomplished on compile-time if beans and dependencies are known on compile-time. As a matter of fact, we don’t have to use run-time dependency resolution in most cases. For example, beans can be created from scratch on run-time in Spring framework. If you don’t want something like this, then compile-time dependency resolution could be opted.</p><p>Dependency resolution step validates and creates dependency graph. Since dependency graph is validated in compile time, errors can be caught while compiling the application. That would mean you don’t have to run the application to spot a misconfigured bean. After dependency graph is created, it can be turned to a static code for creating and injecting bean.</p><p>Let’s take the simple example below. Spring annotations are used for demonstration.</p><p><em>ServiceA</em> and <em>ServiceB</em> beans implementing <em>Service</em> interface are created. They are described with different qualifiers. <em>ServiceA</em> has Singleton and <em>ServiceB</em> has prototype scope. A <em>Service</em> object having <em>ServiceB</em> qualification is injected into a client.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3203885d07550fe3858100d3861828f/href">https://medium.com/media/d3203885d07550fe3858100d3861828f/href</a></iframe><p>Based on this dependency configuration, a context class could be implemented. <em>Context</em> includes providers for <em>ServiceA</em>, <em>ServiceB</em> and <em>Client</em> beans. Since <em>ServiceA</em> and <em>Client</em> are singleton, their single instances are kept in static variables. While creating <em>Client</em>, provider of <em>ServiceB</em> is called and injected into it because its dependency is resolved based on <em>Qualifier</em> annotation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12609b1f2b78dd0dc0ebdada664e2ecc/href">https://medium.com/media/12609b1f2b78dd0dc0ebdada664e2ecc/href</a></iframe><p>This context can be used directly in an entry point of the application to obtain beans.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c80293f6b3a6bb3ef98a1e2a46e1dff/href">https://medium.com/media/0c80293f6b3a6bb3ef98a1e2a46e1dff/href</a></iframe><p>This example demonstrates the concept of compile-time dependency injection in a simple way. Dependencies are resolved in compile time and created with respect to their scope. However, it could get cumbersome with some concepts like run-time profiles and conditional beans. We’ll take a look on another example employing run-time profiles later in the article.</p><p><strong>Dagger</strong></p><p>Dagger is a compile-time dependency injection framework that originally designed for Android platform. It validates dependency graph and generates injector code in compile-time. Components can be obtained using generated code in an entry point of an application using the generated code. <a href="https://square.github.io/dagger">Dagger 1</a> is developed by Square and then taken over by Google. Google has developed <a href="https://github.com/google/dagger">Dagger 2</a> with major improvements.</p><p>Dagger works as an annotation processor during compilation. It supports JSR-330 specification. On top of that, it has own annotations and logic for specific or higher-level constructs. These are the main annotations for building an application with Dagger:</p><p><em>@Inject</em>: Specifies dependency injection points as well as declares a bean</p><p><em>@Provides</em>: Declares a bean by providing factory method in a module</p><p><em>@Binds</em>: Declares a bean by binding to another bean in a module</p><p><em>@Module</em>: Annotates a class where logically-related beans are declared</p><p><em>@Component</em>: Annotates an interface for defining beans to be provided in context</p><p><em>@Scope</em>: Declares scope of a bean as well as a component</p><p><em>@Singleton</em>: Declares a singleton-scoped bean</p><p>Dagger also provides further concepts like subcomponents, assisted injection, lazy and asynchronous injection. However, some concepts such as application profiles, conditional beans, expression language are missing when compared dependency-injection frameworks like Spring.</p><p>Concepts like application profiles and conditional beans might not seem to be viable with a compile-time dependency injection like Dagger at first glance. However, compile-time dependency resolution and validation is still possible since all possible scenarios induced by run-time conditions are known. Hence for each case different static injection configurations can be created at compile time. After that, corresponding configuration be only chosen at run-time.</p><p><strong>Multi-Profile Application Example</strong></p><p>A Dagger application implementing multiple application profiles is demonstrated in the below example. It is a simple console CRUD application having development and production profiles. It authenticates user and execute CRUD operations via a console interface. Let’s assume that application has different external configuration files, authentication information and database types for each environment. Also only production environment contains metrics publishing component for better production-readiness. You can find the source code of the application <a href="https://github.com/deepend0/examples/tree/master/daggermultiprofile">here</a>.</p><p>Application has three dependencies and they are injected in the constructor:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca4fe7dfb1679206c6d90450873d521c/href">https://medium.com/media/ca4fe7dfb1679206c6d90450873d521c/href</a></iframe><p>Since Dagger modules are logical groups of beans, they might be broken down and combined differently. For this example, we have modules for profile info, common, development and production profiles. Profile info module is required to supply profile information when resolving the configuration at the entry point of application. Here profile information is get from an environment variable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e6cf75b7658e57e51420522638c10b8/href">https://medium.com/media/4e6cf75b7658e57e51420522638c10b8/href</a></iframe><p>Common module stands for common components among profiles. Here we have loaded external config data, authentication component and optional metrics publisher. Authentication component reading from static configuration file is bound to <em>ApplicationComponent</em> interface using <em>@Binds</em> annotation. Since only production profile has <em>MetricsPublisher</em>, it is declared with <em>@BindsOptionalOf</em> annotation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d023dce086d03c33dec3cf19841b01c/href">https://medium.com/media/5d023dce086d03c33dec3cf19841b01c/href</a></iframe><p>Development and production modules contain profile-specific configurations. In development module, there is only in-memory data source is defined.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9884385a0ffd367e2b54ba41fb48b40a/href">https://medium.com/media/9884385a0ffd367e2b54ba41fb48b40a/href</a></iframe><p>In production module dbms server is defined as data source and metrics publisher is present.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c732979f701f93b98fd1ff738acc001a/href">https://medium.com/media/c732979f701f93b98fd1ff738acc001a/href</a></iframe><p>Components in Dagger plays the injector role in dependency-injection pattern. Based on declared types to obtain in component interface, dagger generate factory methods that creates desired component by injecting other beans. Here we have main component and profile components. Profile components are designated as subcomponents. Subcomponent is another notion in Dagger that they inherit dependencies from its parent. Its scope is interleaved within the scope of the parent. That means parent component should be always present during subcomponent lifetime, but not vice versa. A builder or factory method is required when declaring subcomponents.</p><p>Profile components include the main application class, which is the main bean for all other dependencies in the application. However, profile-specific dependencies will be injected within these components to compose it. Development component installs common and development modules, where as production component installs common and production modules. In addition, a builder interface must be declared for subcomponents.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e28cf860abbc68255b68ff77d3666fea/href">https://medium.com/media/e28cf860abbc68255b68ff77d3666fea/href</a></iframe><p>In Dagger, modules for subcomponents should also be created in order for subcomponents to be linked to parent components. Hence, we have this marker modules.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1acfe734f325748047ba06aecdbe6abc/href">https://medium.com/media/1acfe734f325748047ba06aecdbe6abc/href</a></iframe><p>On top of all those modules and components, main component is defined. It declares only profile information as a bean. Otherwise, profile-specific subcomponent builders are declared.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/336269c16b3ab1b142c9d3090526d377/href">https://medium.com/media/336269c16b3ab1b142c9d3090526d377/href</a></iframe><p>As a last component, we have a class for profile resolution where main application class with injected profile-specific beans is obtained. This class is also the only place where Dagger-generated component factory class is statically used. Her DaggerMainComponent.create() factory method to obtain MainComponent. After creating main component, each profile is mapped to a supplier that builds profile-specific component and then returns the application bean.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/753c977bfcf53cc6e2b8e72e2e62f45c/href">https://medium.com/media/753c977bfcf53cc6e2b8e72e2e62f45c/href</a></iframe><p>Finally, whole application is run from an entry of the application as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee7f86a6fc5e4d62a25440996b025b73/href">https://medium.com/media/ee7f86a6fc5e4d62a25440996b025b73/href</a></iframe><p><strong>Conclusion</strong></p><p>If all dependencies are predetermined in compile-time, compile time dependency injection can be used for improving application performance by handling dependency resolution in compile-time and avoiding run-time type information mechanisms like reflection. Even if dependencies are bound to certain run-time conditions, separate configurations can be created for each condition on compile time.</p><p>Dagger is a compile-time dependency injection framework for Java. In this article, a multi-profile application example is created using Dagger. The application is tied to run-time profiles. For each profile, a separate Dagger subcomponent is created and main application class is declared on that. Based on profile information, the application class is obtained from one of those components.</p><p>Dagger is a cool framework to consolidate compile-time dependency injection concept. However, in this article we implemented a run-time condition based, multi-profile application manually. Run-time profiles and conditional dependencies features can be added into Dagger as a significant improvement such that all that boilerplate code we implemented will be removed.</p><p><strong>Resources</strong></p><p>Dagger Official Documentation</p><p><a href="https://dagger.dev/">https://dagger.dev/</a></p><p>DAGGER 2 — A New Type of dependency injection</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fembed%2FoK_XtfXPkqw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fwatch%3Fv%3DoK_XtfXPkqw&amp;image=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fi.ytimg.com%2Fvi%2FoK_XtfXPkqw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c9a1fcd0beefa178c377d9d6bec4941/href">https://medium.com/media/8c9a1fcd0beefa178c377d9d6bec4941/href</a></iframe><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bddeb51e8242" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/compile-time-dependency-injection-using-dagger-bddeb51e8242">Compile-Time Dependency Injection with Dagger 2</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[Java Language Nuances and Intricacies]]></title>
            <link>https://deependdev.medium.com/java-language-nuances-and-intricacies-347d919f33a9?source=rss-75019b2ce370------2</link>
            <guid isPermaLink="false">https://medium.com/p/347d919f33a9</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Orkun Akile]]></dc:creator>
            <pubDate>Thu, 27 May 2021 07:56:01 GMT</pubDate>
            <atom:updated>2021-05-27T14:25:27.361Z</atom:updated>
            <content:encoded><![CDATA[<p>Java is complete and thorough as regards of implemented features. Each construct or mechanism is implemented full-blown considering many cases. Therefore complicated issues are addressed within itself elaborately. Delving into those elaborations is an enabler for more effective and advanced command of Java language. However they may not be obvious in daily development routine even for experienced developers. Once in a while, someone encounters a compiler error or weird run-time behavior and becomes aware of them. For that, it is worthwhile examining them to have a complete sense. In addition, examining those are quite beneficial for preparing for Oracle’s Java certification, since the certification exam is mostly about rules and properties of the language to a large extent.</p><p>In this article, nuances and intricacies about 10 features of Java language are presented. These are comprised of rules and properties pertaining to language constructs, mechanisms. It is intended to demonstrate specifics and edge cases for each issue. As a software engineer having an extensive experience on Java, I have chosen ones seemed interesting by trying to cover different parts of the language.</p><p><strong>Initializer Blocks</strong></p><p>A member variable can be initialized in a declaration statement, initializer block or constructor. It could be relatively complicated when inheritance, inner classes and mixed usages are taken into account. There are rules applying to initialization.</p><ul><li>Static initializers are run in class loading phase. Instance initializers are run while an object is being constructed.</li><li>Initialization in declaration and initializer blocks are executed in the order they appeared in the code. There could be multiple initializer blocks and they can be interleaved with declaration statements.</li><li>Constructor block is executed after initializer blocks.</li><li>Initializers of parent classes are executed before child.</li><li>Related with class loading, static initializers of outer classes are executed before static initializers of static nested classes. However, there is a special case here. If a static member variable of a nested class is assigned both in outer and nested class initializers, assignment in that of nested class takes place first.</li></ul><p>When all these rules are combined, difficult cases can occur. Let’s look at a few examples.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/255dd8fa28e3cb1910c6ff8bcb81c07f/href">https://medium.com/media/255dd8fa28e3cb1910c6ff8bcb81c07f/href</a></iframe><p>The output of executing main method in the above code will be:</p><pre>Static Initializer Block<br>Initializer Block<br>Constructor Block</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6be4d97c98970741240062381537c8e/href">https://medium.com/media/b6be4d97c98970741240062381537c8e/href</a></iframe><p>The output of executing main method in the above code will be:</p><pre><br>staticMemberA: 5<br>staticMemberB: 10<br>staticMemberC: 20<br>instanceMemberA: 104<br>instanceMemberB: 201<br>instanceMemberC: 302<br>instanceMemberD: 402</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1fdfbf7e75a3068c669274d45b5559cf/href">https://medium.com/media/1fdfbf7e75a3068c669274d45b5559cf/href</a></iframe><p>The output of executing main method in the above code will be:</p><pre>Parent Init<br>Outer Init<br>Inner Init<br>classMemberP1: 1<br>classMemberP2: 20<br>classMemberP3: 300<br>classMemberO1: 60<br>classMemberO2: 70<br>classMemberO2: 800<br>Inner1.classMemberI1: 400<br>Inner2.classMemberI2: 500</pre><p><strong>Overloaded Method Resolution</strong></p><p>Resolution of an overloaded method can be tricky. Multiple overloaded methods might be suitable for a parameter list. For example, in case of numeric types, mechanisms such as numeric promotion, auto-boxing, var-args, inheritance could be applied to parameters to match target types. Otherwise, for reference types, overloaded methods for both parent and child classes may be present. Since ambiguity has no place in a programming language, there are rules to resolve that problem.</p><p>When no exact match is found, the first rule is that method having the least implicit type conversion steps is selected. For example, int parameter can be applied both to long and Number parameter types. However, only numeric promotion is necessary to obtain long of int, whereas boxing and generalization should be applied for Number type. Therefore, method with long type is selected.</p><p>Second rule is selecting the method with most specific/closest parameter types. For example, regarding a short parameter, int is closer to it than long parameter type. As another example, regarding ArrayList parameter, List type is closer to it than Collection parameter type.</p><p>As the last rule, even ambiguity persists after first two , the following order is applied to obtain target parameters: numeric promotion, auto-boxing, inheritance and var-args. Since var-args is a relatively new language feature (since Java 5), it takes the lower priority.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5f064ec449e53b7c87032f63fb3811c/href">https://medium.com/media/b5f064ec449e53b7c87032f63fb3811c/href</a></iframe><p>The output of executing main method in the above code will be:</p><pre>short param<br>long param<br>Object param<br>Object param</pre><p><strong>Hiding, Shadowing and Obscuring</strong></p><p>If a member of a class becomes invisible via inheritance, it is called member hiding. Three member types can be hidden: static methods, static variables and instance variables. Instance methods cannot be hidden, they are overridden. Static and instance variables can cause hiding for each other as well. Hidden members can be accessed via super keyword within the subclass, otherwise via type-casting from outside.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d7a3e45dcb0d709fb39645711be2b0e/href">https://medium.com/media/5d7a3e45dcb0d709fb39645711be2b0e/href</a></iframe><p>The output of executing main method in the above code will be:</p><pre>10<br>20<br>30<br>Child<br>1<br>2<br>3<br>Parent</pre><p>On the other hand, if a member becomes invisible because of scoping, it is member shadowing. Member shadowing can occur in methods or inner classes. When a local variable is defined with the same name as an instance variable, instance variable is shadowed. It can be accessed using <em>this</em> keyword. Also when any member with the same name/signature is defined within an inner class as a member or local variable, this also causes shadowing. Member in the outer element can be accessed using <em>ClassName.this</em> notation. Even in case of many nested levels, members belong to a certain nested class can be accessed using this statement.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e992a381bcd7ebbb78abd7407cd2aa7d/href">https://medium.com/media/e992a381bcd7ebbb78abd7407cd2aa7d/href</a></iframe><p>The output of executing main method in the above code will be:</p><pre>local intMember: 10<br>instance intMember: 1<br>inner local intMember: 101<br>inner instance intMember: 100<br>outer instance intMember: 1<br>inner instance method: 20<br>outer instance method: 2</pre><p>Obscuring is a problem occurring when a variable name is declared the same as a class name. Due to precedence rules, the class may not be accessed directly but via fully qualified name. The following code will cause compile error.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7368f9eff971fae90e5b274a92f81a34/href">https://medium.com/media/7368f9eff971fae90e5b274a92f81a34/href</a></iframe><p><strong>String Pool Usage</strong></p><p>Since String objects are immutable, string pool is in action to achieve better efficiency. There are also confusing cases about string pool usage. It is straightforward to know that string literals are used from the pool. What about other cases such as creating strings using String class or producing strings as a result of operations? The key rule here is that only compile time constant expressions are obtained from string pool. Let’s take a look at examples:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c3212f7ab6c7fef1f29fa7445878110/href">https://medium.com/media/0c3212f7ab6c7fef1f29fa7445878110/href</a></iframe><p>The output of executing main method in the above code will be:</p><pre>true<br>false<br>true<br>false<br>false<br>false<br>false<br>true</pre><p>String a and b are assigned to a string literal, therefore they are the same objects. Apart from that, only string d is assigned to a compile time constant expression with concat operator in declaration.</p><p>String class has also intern method to return the equivalent object from the pool, or add to the pool as a new object if doesn’t exist.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d33237226b99704d9b67212a62fdd936/href">https://medium.com/media/d33237226b99704d9b67212a62fdd936/href</a></iframe><p>The output of executing main method in the above code will be:</p><pre>false<br>false<br>true</pre><p><strong>Interface Methods</strong></p><p>Prior to Java 8, interfaces could only have public abstract methods. As of Java 8, public default and public static methods are involved. Even further, from Java 9 and onward, private and private static methods can be part of interfaces.</p><p>Newly-allowed methods are used as they are for other classes. However, there is a complicated case about default methods. It is actually a multiple inheritance problem and occurs when multiple interfaces are implemented. In this case, if the same default methods exists more than once in implemented methods, that method must be overridden by the subclass. But that doesn’t happen when the same method exists in an inherited class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e41c87f33e55f4bc1f5ef127bba2a653/href">https://medium.com/media/e41c87f33e55f4bc1f5ef127bba2a653/href</a></iframe><p>Also these conflicting default method declarations are reachable in the subclass using following syntax:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a83a7cc0a6ae08e1101acd528d15967/href">https://medium.com/media/6a83a7cc0a6ae08e1101acd528d15967/href</a></iframe><p>Another point is that a public static method in the interface can be used only with the name of the interface in the subclass, whereas class names aren’t necessary when static methods from parent classes are used.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afd0d35e27c78771061cd33094279742/href">https://medium.com/media/afd0d35e27c78771061cd33094279742/href</a></iframe><p><strong>try-with-resources Statement</strong></p><p>try-with-resources statement is a convenient way of accessing resources requiring to be released after use. It also has a few complicated use cases handled by Java language.</p><p>What if there are dependencies between resources? In that case resources must be released in reverse order they obtained. That is what is done with try-with-resources statement with multiple resources. Actually it works like nested statements.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5999ad1675d08434eb0fc8dc28b6f15/href">https://medium.com/media/e5999ad1675d08434eb0fc8dc28b6f15/href</a></iframe><p>Another case occurs based on the fact that closing resources may also raise an exception that can be handled in one of the catch blocks. However, an exception also may be thrown inside of try block. In that case, we would have two exceptions to handle. Suppressed exception notion takes place here. The exception thrown in try block will be handled mainly with the exception occurred when closing the resource attached as a suppressed exception.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa19bb55ac9ebf104b979efd27e33529/href">https://medium.com/media/aa19bb55ac9ebf104b979efd27e33529/href</a></iframe><p>The output of executing main method in the above code will be like this:</p><pre>ArithmeticException occured.<br>java.lang.ArithmeticException: / by zero<br> at javanuances/org.example.AccessResource.main(TryWithResources.java:34)<br> Suppressed: java.lang.Exception: Cannot close resource<br> at javanuances/org.example.Resource1.close(TryWithResources.java:27)<br> at javanuances/org.example.AccessResource.main(TryWithResources.java:33)</pre><p><strong>Generics Type Erasure</strong></p><p>Since type parameters aren’t available in runtime due to type erasure in Java, some operations cannot be done with them such as creating new object, creating array or type check with instanceof operator.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2094a919876e133a14676c6086d2002/href">https://medium.com/media/e2094a919876e133a14676c6086d2002/href</a></iframe><p>Besides, overloading with different type parameters is not possible because of type erasure again. With this view point, overriding with different type parameters may seem possible but it is also not allowed. The following snippet exemplifies illegal overloading and overriding:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bf63662a3a8f9d61728f75fd0782207/href">https://medium.com/media/3bf63662a3a8f9d61728f75fd0782207/href</a></iframe><p>Type parameters cannot be obtained using reflection as expected. And a class object with generic type is not available as well like Generic1&lt;Integer&gt;.class.</p><p><strong>Nested Class Rules</strong></p><p>Nested classes can be declared in four forms: inner class, static nested class, local class, anonymous class. Inner classes are member classes attached to instances whereas static nested classes are member classes attached to class. Local classes are declared in methods or initializer blocks. Anonymous classes are special type of local classes that are created during an assignment only to extend a class or implement a method anonymously.</p><p>Permitted modifiers and member types may vary according to the type of nested class and this could be puzzling. These are the rules that apply:</p><ul><li>Inner classes and static nested classes may take all access modifiers as well as final and static modifier. However local classes may take abstract and final modifiers whereas anonymous classes may not take any of them.</li><li>Static nested classes may have all types of members such as static/instance variables or methods. On the other hand inner classes, local classes and anonymous classes may only have instance variables/methods or static final variables.</li><li>Nested classes except anonymous classes can implement interfaces or extend any class, but anonymous classes cannot.</li><li>Interfaces cannot have inner classes but can have public static nested classes.</li><li>Only static nested interfaces can be declared within any class or interface.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28feb45e8f6e7154fe89e4be38f56d70/href">https://medium.com/media/28feb45e8f6e7154fe89e4be38f56d70/href</a></iframe><p><strong>Annotation Targets</strong></p><p>When creating an annotation, usage of annotations can be restricted using @Target annotation in a detailed manner. It takes a value of ElementType enumeration. Elements of ElementType are:</p><pre>TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, ANNOTATION_TYPE, TYPE_PARAMETER, TYPE_USE, PACKAGE, MODULE</pre><p>Names of the most ElementType values convey the scope in direct manner. They are applied to any declaration of covered element. For instance, TYPE applies to any type declaration including classes, interfaces, enums and annotations. Also some of the element types overlap, such as METHOD and CONSTRUCTOR.</p><p>However, TYPE_USE target element type is relatively complex. It applies everywhere a declared type is used. According to Java language specification (https://docs.oracle.com/javase/specs/jls/se11/html/jls-4.html#jls-4.11), there are 16 cases where types are used. It covers most of the other ElementType values. However, there are a few exceptions. For example, it cannot be used with methods without a return type. In addition to those, it can be used in extends/implements clauses, type casts, object construction etc.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f61ffb9f1df08fedd01f3201053ce87f/href">https://medium.com/media/f61ffb9f1df08fedd01f3201053ce87f/href</a></iframe><p>By default, element type is union of all element types except for TYPE_USE. Therefore it should always be explicitly given.</p><p><strong>Module System</strong></p><p>A module is a set of related java packages containing types, data files and static resources. It is introduced to promote encapsulation and modularity as of Java 9. However, module concept alters behavior of Java in a few ways.</p><p>Firstly, types in packages that are not exposed by a module cannot be accessed by other packages even via reflection. Without module system, all members of all types could be accessed via reflection including private ones. Packages can be exposed using exporting or opening statements: <em>exports</em>, <em>exports … to</em>, <em>open</em>, <em>opens,</em> <em>opens … to</em>. Exports statement allows access to the types both in compile time and run-time whereas opens statement only allows in runtime. That means opens statement only allows accessing a type via reflection.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62eff17857a0ef6a0c497d7b79e213d5/href">https://medium.com/media/62eff17857a0ef6a0c497d7b79e213d5/href</a></iframe><p>Split packages are not allowed with module system. That means a specific package can only be exported by only one module. If none of the modules exports the same package, it doesn’t create a problem. If either or both of them exports the package, that will cause compilation error. The following scenario, module declarations cause a compile error.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3013e86461c5319b65db422722cf7203/href">https://medium.com/media/3013e86461c5319b65db422722cf7203/href</a></iframe><pre>./moduleB/src/main/java/com/company/app/partialpackage/ModuleBClass.java:1: error: package exists in another module: mod1<br>package com.company.app.partialpackage;</pre><p>Cyclic dependencies are also not allowed within modules.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f372f0db97aac235f5b7ea79056df259/href">https://medium.com/media/f372f0db97aac235f5b7ea79056df259/href</a></iframe><pre>./moduleC/src/main/java/module-info.java:3: error: cyclic dependence involving moduleB<br> requires moduleB;<br> ^<br>./moduleA/src/main/java/module-info.java:3: error: cyclic dependence involving moduleC<br> requires moduleC;<br> ^<br>./moduleB/src/main/java/module-info.java:3: error: cyclic dependence involving moduleA<br> requires moduleA;<br> ^</pre><p><strong>Conclusion</strong></p><p>Several nuances and intricate parts of Java are explained and demonstrated through this article. There could be found more of them in the language when it is examined and dug in. Other specifics can be deducted by inspecting Java language specification and Java docs. They are useful for fully and comfortably harnessing of language and satisfying our analytical minds. Let’s keep up that inquisitive and sharp mind in programming!</p><p><a href="https://docs.oracle.com/javase/specs/jls/se11/html/index.html">The Java® Language Specification</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=347d919f33a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>