<?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 Weberton Faria on Medium]]></title>
        <description><![CDATA[Stories by Weberton Faria on Medium]]></description>
        <link>https://medium.com/@webertoneugenio.defaria?source=rss-6d10b4218227------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*k3l6NMCSZv-OSZyK</url>
            <title>Stories by Weberton Faria on Medium</title>
            <link>https://medium.com/@webertoneugenio.defaria?source=rss-6d10b4218227------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 12:26:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@webertoneugenio.defaria/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[Cycle Detection in Linked Lists: Essential Algorithms Unveiled]]></title>
            <link>https://medium.com/@webertoneugenio.defaria/cycle-detection-in-linked-lists-essential-algorithms-unveiled-2b62c992a1b4?source=rss-6d10b4218227------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b62c992a1b4</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[linked-lists]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Weberton Faria]]></dc:creator>
            <pubDate>Tue, 14 Oct 2025 19:19:14 GMT</pubDate>
            <atom:updated>2025-10-14T19:19:14.563Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>This article explores the challenge of detecting cycles in linked lists, a simple but fundamental concept in computer science and a frequent problem in software development interviews. Through my experience, I’ve encountered this problem firsthand in a technical interview, underscoring its practical importance. The article aims to provide clear and insightful solutions to help understand and solve this problem effectively.</p><p>To facilitate a comprehensive understanding, we will explore practical solutions accompanied by illustrative examples in Java and Python.</p><h3><strong>The Problem</strong></h3><p>The issue is determining whether a cycle exists within a linked list. In essence, a linked list is a linear data structure where each node not only holds a value but also a pointer directing to the subsequent node. Under ideal circumstances, the last node of a linked list should point to null, signaling the list’s conclusion. However, complications arise when a node links back to an earlier one in the list, forming a cycle. This scenario can lead to significant problems, such as endless loops.</p><p>An illustrative diagram below demonstrates a linked list entangled in such a cycle.</p><figure><img alt="Graphic of a linked list showing a cycle, where node values 8, 10, 5, 1 are connected sequentially and the last node loops back to the second node." src="https://cdn-images-1.medium.com/max/1024/1*LIFcVb6amO5G0sGg7rzomQ.png" /><figcaption>Linked List with a Cycle</figcaption></figure><p>To detect a cycle within a linked list, one efficient method is to employ a Set to record each visited node. As we navigate through the list, we add every node we encounter into the Set. Encountering a node that has already been added to the Set signals that a cycle exists.</p><h3>Using a Set to Store Visited Nodes: Java Code Example</h3><pre>import java.util.HashSet;<br>import java.util.Set;<br><br>public class LinkedListCycle {<br><br>    public static boolean containsCycle(Node head) {<br>        Set&lt;Node&gt; visited = new HashSet&lt;&gt;();<br>        Node currentNode = head;<br><br>        while (currentNode != null) {<br>            if (visited.contains(currentNode)) {<br>                return true;<br>            }<br><br>            visited.add(currentNode);<br>            currentNode = currentNode.next;<br>        }<br>        return false;<br>    }<br><br>    public static void main(String[] args) {<br>        Node n8 = new Node(8);<br>        Node n10 = new Node(10);<br>        Node n5 = new Node(5);<br>        Node n1 = new Node(1);<br><br>        n8.next = n10;<br>        n10.next = n5;<br>        n5.next = n1;<br>        n1.next = n10;<br><br>        System.out.println(containsCycle(n8));<br>    }<br>}<br><br>class Node {<br>    int value;<br>    Node next;<br><br>    public Node(int value) {<br>        this.value = value;<br>        this.next = null;<br>    }<br>}</pre><h4>Using a Set to Store Visited Nodes: Complexity Analysis</h4><p><strong>Time Complexity Analysis</strong></p><ul><li><strong>Set Operations</strong>: Insertion and search in a Set typically have an average time complexity of O(1), thanks to hashing which facilitates quick access operations.</li><li><strong>Traversal of the Linked List</strong>: Each node in the list is visited only once, with a search and possibly an insertion in the Set being performed at each node.</li><li><strong>Overall Time</strong>: For a linked list with ’N’ nodes, the total time complexity is O(n), as each node is accessed once, and for each node, the operations on the Set are executed in constant time.</li></ul><p><strong>Space Complexity Analysis</strong></p><ul><li><strong>Storing Visited Nodes:</strong> The proposed solution uses a Set (in Java) to track the visited nodes in the linked list. The additional space used is for storing these nodes in the Set.</li><li><strong>Total Space Usage:</strong> In the worst-case scenario, where there’s no cycle, all nodes will be added to the Set. Hence, the worst-case space complexity is O(n), where ’n’ is the total number of nodes in the linked list.</li></ul><h3>Solution 2: The Two-Pointer Technique for Cycle Detection</h3><p>This method employs two pointers moving at different speeds through the list — one faster and one slower. If there’s a cycle in the list, the faster pointer will eventually catch up to the slower one, indicating the presence of a cycle</p><pre>public class LinkedListCycle {<br>    <br>    public static boolean containsCycle(Node head) {<br>        if (head == null) return false;<br><br>        Node slow = head;<br>        Node faster = head.next;<br><br>        while (faster != null &amp;&amp; faster.next != null) {<br>            if (faster == slow) {<br>                return true; // Cycle detected<br>            }<br>            slow = slow.next;                  // Move one step<br>            faster = faster.next.next;        // Move two steps<br>        }<br><br>        return false; //No cycle detected<br>    }<br><br>    public static void main(String[] args) {<br>        Node n8 = new Node(8);<br>        Node n10 = new Node(10);<br>        Node n5 = new Node(5);<br>        Node n1 = new Node(1);<br><br>        n8.next = n10;<br>        n10.next = n5;<br>        n5.next = n1;<br>        n1.next = n10;<br><br>        System.out.println(containsCycle(n8));<br>    }<br>}<br><br>class Node {<br>    int value;<br>    Node next;<br><br>    public Node(int value) {<br>        this.value = value;<br>        this.next = null;<br>    }<br>}</pre><h3>The Two-Pointer Technique for Cycle Detection: Complexity Analysis</h3><p><strong>Time Complexity Analysis</strong></p><p>In this solution, two pointers moving at different speeds are used in the linked list — one ‘slow’ and one ‘fast’.</p><ul><li><strong>Scenario without a cycle: </strong>In this scenario the fast pointer will reach the end of the list. Since the fast pointer moves two steps at a time and the slow one step, the maximum iterations are less than <strong>2N</strong>, where <strong>N</strong> is the number of nodes.</li><li><strong>Cyclic scenario:</strong> In a cyclic scenario, the fast pointer will eventually catch up to the slow pointer inside the cycle. The iterations depend on the cycle’s size and start position but are significantly fewer than <strong>2N</strong>.</li></ul><p>Thus, the general time complexity is O(n), where n is the number of nodes.</p><p><strong>Space Complexity Analysis</strong></p><p>The main advantage of this two-pointer solution is its minimal additional space requirement, regardless of the linked list size. It uses only two extra pointers, independent of the number of nodes in the list. Consequently, the total space complexity is O(1), indicating that the space used does not increase with the size of the linked list.</p><h3>Conclusion</h3><p>In this article, we’ve delved into two effective methods for detecting cycles in linked lists — a frequent challenge in technical interviews for top tech companies. The Set-based solution offers simplicity and time efficiency, while the two-pointer method excels in space efficiency. Both have their unique strengths, allowing choice based on specific problem needs and constraints.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b62c992a1b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[gRPC: Build Efficient and Scalable Microservices]]></title>
            <link>https://medium.com/@webertoneugenio.defaria/grpc-build-efficient-and-scalable-microservices-cd9953fc169e?source=rss-6d10b4218227------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd9953fc169e</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[http2]]></category>
            <dc:creator><![CDATA[Weberton Faria]]></dc:creator>
            <pubDate>Sun, 02 Mar 2025 01:03:38 GMT</pubDate>
            <atom:updated>2025-03-02T01:06:48.178Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QkirguFKqAjgD75flZ4TPA.png" /></figure><h3>Introduction</h3><p>In the world of microservices, applications need to communicate frequently — and often in different programming languages. Efficient data exchange is crucial in these scenarios. In this introduction to gRPC, we’ll explore how this technology, developed by Google and part of the Cloud Native Computing Foundation (CNCF), simplifies integration by enabling fast and optimized communication between services.</p><p>📌 <em>This article was originally published on my blog, </em><a href="https://artofcoding.tech/grpc-efficient-scalable-microservices/"><em>Art of Coding</em></a><em>. If you enjoy content on microservices, Java, and software development, check it out!</em></p><p>In this article, we’ll cover the fundamental concepts of gRPC, its key advantages, and how to define a service using Protocol Buffers. Before jumping into a practical example, it’s important to understand the basics and benefits of gRPC. This knowledge will make the development process more intuitive and efficient.</p><h3>Why HTTP/2 is Essential for gRPC</h3><p>HTTP/2 introduces several improvements over HTTP/1.1, making it the ideal choice for gRPC. While HTTP/1.1 opens a new connection for each request and follows a strict request-response model, HTTP/2 offers key advantages that make communication faster and more efficient.</p><p>Here are some of the main benefits:</p><ul><li><strong>Single Connection &amp; Multiplexing:</strong> In HTTP/1.1, each request requires a separate connection, increasing latency. With HTTP/2, multiplexing allows the client and server to send multiple messages in parallel over a single connection, significantly reducing latency.</li><li><strong>Header Compression:</strong> Unlike HTTP/1.1, which sends headers as plain text, HTTP/2 compresses them. This reduces network traffic and improves performance.</li><li><strong>Bidirectional Communication:</strong> HTTP/2 enables the server to send messages directly to the client, supporting more dynamic and proactive interactions. In contrast, HTTP/1.1 only allows servers to respond to requests.</li><li><strong>Binary vs. Text Protocol:</strong> Another key difference is that HTTP/2 uses a binary protocol, ensuring faster and more efficient communication. Meanwhile, HTTP/1.1 relies on plain text.</li><li><strong>Built-in SSL:</strong> Security is a priority in HTTP/2. It was designed with SSL/TLS as a default requirement, ensuring that all communication is encrypted.</li></ul><p>These improvements make HTTP/2 both more efficient and secure, reducing latency and optimizing communication between microservices — critical factors for any system using gRPC.</p><h3>What is gRPC?</h3><p>gRPC is a free and open-source framework that simplifies communication between services, especially in microservices architectures. It allows applications — regardless of programming language — to exchange data quickly and efficiently.</p><p>It is built on Remote Procedure Calls (RPC), allowing a service to execute a function on another system as if it were local. By abstracting remote communication complexities, gRPC simplifies system integration and improves efficiency.</p><p>Beyond being free and open-source, gRPC is designed for speed. It runs on HTTP/2, which offers low latency and real-time communication through multiplexing. This makes gRPC an ideal choice for high-performance systems.</p><p>Another key feature of gRPC is its <strong>support for streaming</strong>. Clients and servers can exchange data continuously, which is essential for real-time updates. Additionally, gRPC is compatible with multiple programming languages, making it easier to implement across different technologies.</p><h3>Protocol Buffers: The Foundation of gRPC</h3><p>To define and structure the messages exchanged between client and server, gRPC uses <strong>Protocol Buffers (Protobuf)</strong>. Protobuf is a lightweight and efficient method for <strong>serializing data</strong>, meaning it converts information into a format that can be easily transmitted and interpreted.</p><p>With Protobuf, you create a <strong>.proto file</strong>, where you define the messages and operations that your gRPC service will support. In other words, this file acts as a <strong>contract</strong>, ensuring that the data sent and received always follows the expected format. By enforcing this structure, Protobuf helps reduce communication errors between different systems.</p><h3>Protocol Buffers in gRPC: Defining Your Service</h3><p>To illustrate how gRPC uses Protocol Buffers to define message structures and services, let’s create a simple example. The .proto file below defines a greeting service called <strong>HelloWorldService</strong>, which has a method <strong>SayHello</strong> to send a personalized message. This example will help us better understand how to configure a basic gRPC service.</p><pre>syntax = &quot;proto3&quot;;<br>package helloworld;<br><br>// Defines the request message<br>message HelloWorldRequest {<br>  string name = 1;<br>}<br><br>// Defines the response message<br>message HelloWorldResponse {<br>  string message = 1;<br>}<br><br>// Defines the service<br>service HelloWorldService {<br>  rpc SayHello(HelloWorldRequest) returns (HelloWorldResponse) {};<br>}</pre><h4>Understanding the Key Components</h4><ul><li><strong>Package </strong><strong>helloworld</strong> – Organizes the file within the project, which is useful when working with multiple services.</li><li><strong>Messages HelloWorldRequest and HelloWorldResponse</strong> — HelloWorldRequest takes a <strong>name</strong> as input, while HelloWorldResponse returns a personalized greeting message to the client.</li><li><strong>Service </strong><strong>HelloWorldService</strong> – This is the main gRPC service. It defines the SayHello method, which takes a HelloWorldRequest and returns a HelloWorldResponse. The client sends a name, and the server responds with a personalized greeting.</li></ul><p>One of gRPC’s biggest advantages is that it <strong>automatically generates the necessary client and server code</strong> based on the .proto file. This generated code supports multiple programming languages, including <strong>Java, Python, C++, and more</strong>, making integration across different technologies seamless.</p><p>By handling the communication setup automatically and consistently, gRPC reduces development time and minimizes errors, ensuring a more efficient and reliable implementation.</p><p>The following image illustrates the communication flow using Protocol Buffers.</p><figure><img alt="A gRPC Java service architecture diagram illustrating microservices communication using Protocol Buffers and HTTP/2 for high-performance APIs.Image Source: gRPC.io" src="https://cdn-images-1.medium.com/max/552/1*sn2nhjtoqqkczMUFPZAE-Q.png" /><figcaption>Image Source: gRPC.io</figcaption></figure><h3>gRPC vs REST: When and Why to Use gRPC</h3><p>gRPC offers several advantages over traditional REST and is ideal for specific scenarios. Below are some situations where gRPC might be the <strong>better choice</strong>:</p><h4>Low Latency and High Performance</h4><p>Thanks to HTTP/2 and support for bidirectional communication with multiplexing, gRPC is more efficient than REST when minimal latency and fast communication are required.</p><h4>Binary Data Transmission</h4><p>While REST typically transmits data in text formats like JSON or XML, gRPC uses a binary format, which is more compact and faster to process. This reduces transmission time and bandwidth usage, making gRPC ideal for systems handling large data volumes.</p><h4>Compact API Definitions</h4><p>Unlike REST APIs, which often use OpenAPI and can be quite verbose, gRPC relies on Protocol Buffers, which are more compact and efficient for defining messages and services. This reduces API complexity and makes development and maintenance easier.</p><h4>Streaming Support</h4><p>gRPC enables continuous data streaming between client and server, making it an excellent choice for applications that require real-time updates, such as messaging services or live data monitoring.</p><h4>Cross-Platform Compatibility</h4><p>With support for multiple programming languages, gRPC simplifies integration between heterogeneous systems. This makes it a great fit for microservices architectures using different technologies.</p><h3>Typical Use Cases</h3><p>gRPC is particularly useful for:</p><ul><li><strong>Internal microservices</strong> — Facilitating communication between services where low latency is critical.</li><li><strong>Real-time applications</strong> — Supporting constant data exchange, such as media streaming or online gaming.</li><li><strong>High-performance API integrations</strong> — Handling high request rates and fast response times efficiently.</li></ul><h3>Conclusion</h3><p>gRPC is a powerful tool for microservice communication, offering high performance, low latency, and support for multiple programming languages. In this introduction to gRPC, we explored its fundamental concepts, how it leverages HTTP/2 and Protocol Buffers to define messages and services efficiently, and why it is an excellent choice for modern systems that require fast and optimized integration.</p><p>In the next article, we’ll put these concepts into practice with a Java implementation, exploring a Unary request. This hands-on example will demonstrate how gRPC simplifies service communication and optimizes development.</p><p>Stay tuned! Follow the blog and subscribe to get notified about the next article, where we’ll implement a real-world gRPC service in Java!</p><p>📌 <em>This article was originally published on my blog, </em><a href="https://artofcoding.tech/grpc-efficient-scalable-microservices/"><em>Art of Coding</em></a><em>. If you enjoy content on microservices, Java, and software development, check it out!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd9953fc169e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Effective Java Thread Management: A Fun Washroom Example]]></title>
            <link>https://medium.com/justeattakeaway-tech/java-thread-management-957b157dcbf9?source=rss-6d10b4218227------2</link>
            <guid isPermaLink="false">https://medium.com/p/957b157dcbf9</guid>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[mutex]]></category>
            <dc:creator><![CDATA[Weberton Faria]]></dc:creator>
            <pubDate>Sun, 23 Jun 2024 12:54:55 GMT</pubDate>
            <atom:updated>2024-06-23T12:54:55.996Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eho4etdFiA5xalE-a6LVig.jpeg" /></figure><p>My <a href="https://medium.com/justeattakeaway-tech/virtual-threads-in-java-21-boosting-application-scalability-and-performance-32acc64bfaea">previous article</a> explored the exciting world of Virtual threads in Java 21. Virtual threads are a powerful feature that simplifies concurrent programming, making it more efficient and less error-prone. However, before diving deep into advanced topics like Virtual threads, it’s essential to understand the basics of threading and how to manage shared resources effectively.</p><p>One common challenge when working with threads is ensuring that multiple threads can access shared resources without conflicts. This is where synchronization comes into play. To illustrate these fundamental concepts in a fun and relatable way, we’ll use a simple yet amusing example involving a shared washroom.</p><p>In this article, we’ll break down the basics of threading in Java using the washroom example. You’ll learn how to synchronize access to a shared resource, manage thread coordination, and avoid common pitfalls. Let’s dive in!</p><h3>Understanding Threads with the Washroom Example</h3><p>To understand how threading and synchronization work in Java, let’s consider a simple scenario: a shared washroom. In this scenario, we have three types of users:</p><ol><li><strong>People with Quick Needs</strong>: These are the users who need to use the washroom for a short period.</li><li><strong>People with Longer Needs</strong>: These users take a bit more time in the washroom.</li><li><strong>The Cleaner</strong>: This user cleans the washroom, but only when it’s dirty.</li></ol><p>Here are the rules for our washroom:</p><ul><li>Only one person can use the washroom at a time. Whether it’s for quick needs or longer needs, the washroom can only accommodate one user at a time.</li><li>After each use, the washroom is marked as dirty.</li><li>The cleaner checks if the washroom is dirty. If it is, the cleaner will clean it. The cleaner can only clean the washroom when no one else is using it.</li></ul><p>This example is a perfect analogy for understanding how to manage access to a shared resource (the washroom) using threads. We’ll use Java synchronization mechanisms to ensure that only one thread (user) can access the resource at a time and to coordinate the actions of different threads.</p><h3>Writing the Code and Explanation</h3><p>We’ll start by defining the Washroom class and then incrementally add methods to handle quick needs, long needs, and cleaning.</p><h4>Setting Up the Washroom Class</h4><p>First, let’s create the basic structure of the Washroom class:</p><pre>public class Washroom {<br>    private boolean dirty = false; // Indicates if the washroom is dirty<br>}</pre><h4>Handling Quick Needs</h4><p>Next, let’s add a method to handle quick needs in the washroom. This method will:</p><ol><li><strong>Check if the Washroom is Dirty</strong>: If the washroom is dirty, the thread will wait until it is cleaned.</li><li><strong>Use the Washroom</strong>: Once the washroom is available, the thread will simulate a quick need with a short sleep, mark it as dirty, and then finish.</li><li><strong>Notify Other Threads</strong>: After finishing, the thread will notify all waiting threads that the washroom has been used and is now dirty.</li></ol><pre>    // Method for quick needs<br>    public void useWashroomQuick() throws InterruptedException {<br>        String name = Thread.currentThread().getName();<br>        System.out.println(name + &quot; is in line.&quot;);<br><br>        synchronized (this) { // Synchronize on the current instance<br>            while (dirty) {<br>                System.out.println(name + &quot; - washroom is dirty. Waiting to use the washroom (quick need)&quot;);<br>                wait();<br>            }<br>            System.out.println(name + &quot; is using the washroom for quick need&quot;);<br>            Thread.sleep(5000); // Simulate quick need<br>            dirty = true; // Mark washroom as dirty<br>            System.out.println(name + &quot; finished using the washroom&quot;);<br>            notifyAll(); // Notify all waiting threads<br>        }<br>    }</pre><p>This method uses synchronization to ensure that only one thread can execute the critical section at a time. If the washroom is dirty, the thread waits (wait()) until it is notified that the washroom has been cleaned. Once the washroom is available, the thread marks it as dirty and simulates using it with Thread.sleep(5000). After using the washroom, the thread notifies all waiting threads (notifyAll()) that the washroom is now dirty.</p><p>The synchronized is used with this to lock the current instance of the Washroom object. This means that the lock is associated with the specific instance, ensuring that no other thread can enter any synchronized block of code on the same object at the same time. In this context, this acts like a mutex or key that only one thread can hold at a time, ensuring exclusive access to the critical section of code.</p><h4>Handling Long Needs</h4><p>Now, let’s add a method to handle long needs in the washroom. This method follows a similar pattern to the quick needs method but simulates a longer usage time.</p><pre>    // Method for long needs<br>    public void useWashroomLong() throws InterruptedException {<br>        String name = Thread.currentThread().getName();<br>        System.out.println(name + &quot; is in line.&quot;);<br><br>        synchronized (this) {<br>            while (dirty) {<br>                System.out.println(name + &quot; - washroom is dirty. Waiting to use the washroom (long need)&quot;);<br>                wait();<br>            }<br>            System.out.println(name + &quot; is using the washroom for long need&quot;);<br>            Thread.sleep(8000); // Simulate long need<br>            dirty = true;<br>            System.out.println(name + &quot; finished using the washroom&quot;);<br>            notifyAll();<br>        }<br>    }</pre><h4>Cleaning the Washroom</h4><p>Finally, let’s add the method to clean the washroom. This method will check if it is dirty. If the washroom is not dirty, the thread will wait until it is used. Once the washroom is dirty, the thread will clean it and mark it as clean. After cleaning, the thread will notify all waiting threads that the washroom is now clean.</p><pre>    // Method for cleaning the washroom<br>    public void cleanWashroom() throws InterruptedException {<br>        String name = Thread.currentThread().getName();<br>        synchronized (this) {<br>            System.out.println(name + &quot; is checking if the washroom needs cleaning.&quot;);<br>            if (!dirty) {<br>                System.out.println(name + &quot; - washroom is clean. Leaving the washroom.&quot;);<br>                return;<br>            }<br>            System.out.println(name + &quot; is cleaning the washroom&quot;);<br>            Thread.sleep(5000); // Simulate cleaning<br>            dirty = false;<br>            System.out.println(name + &quot; finished cleaning the washroom. Leave the washroom.&quot;);<br>            notifyAll();<br>        }<br>    }</pre><h4>Creating Task Classes for Washroom Simulation</h4><p>We will now create specific task classes for each type of washroom task. Creating specific task classes for each type of washroom task is a good design choice. It makes the code more modular, adheres to the Single Responsibility Principle, and ensures clear separation of concerns. This approach improves readability and maintainability.</p><h4>Defining the WashroomQuickTask</h4><pre>public class WashroomQuickTask implements Runnable {<br>    <br>    private final Washroom washroom;<br><br>    public WashroomQuickTask(Washroom washroom) {<br>        this.washroom = washroom;<br>    }<br><br>    @Override<br>    public void run() {<br>        try {<br>            washroom.useWashroomQuick();<br>        } catch (InterruptedException e) {<br>            throw new RuntimeException(e);<br>        }<br>    }<br>}</pre><h4>Defining the WashroomLongTask</h4><pre>public class WashroomLongTask implements Runnable {<br>    <br>    private final Washroom washroom;<br><br>    public WashroomLongTask(Washroom washroom) {<br>        this.washroom = washroom;<br>    }<br><br>    @Override<br>    public void run() {<br>        try {<br>            washroom.useWashroomLong();<br>        } catch (InterruptedException e) {<br>            throw new RuntimeException(e);<br>        }<br>    }<br>}</pre><h4>Defining the WashroomCleanTask</h4><p>The cleaner task is placed in a while(true) loop to ensure it continuously checks and cleans the washroom as long as the program is running. Without the loop, the cleaner would clean the washroom just once and exit, leaving other tasks potentially waiting indefinitely if the washroom gets dirty again. The while(true) loop keeps the cleaner active and responsive, ensuring that the washroom remains usable for all other tasks.</p><pre>public class WashroomCleanTask implements Runnable {<br><br>    private final Washroom washroom;<br><br>    public WashroomCleanTask(Washroom washroom) {<br>        this.washroom = washroom;<br>    }<br><br>    @Override<br>    public void run() {<br>        while (true) {<br>            try {<br>                washroom.cleanWashroom();<br>                Thread.sleep(5000);<br>            } catch (InterruptedException e) {<br>                throw new RuntimeException(e);<br>            }<br>        }<br>    }<br>}</pre><h4>Running the Scenario</h4><p>Now, let’s create the threads to simulate people using and cleaning the washroom:</p><pre>public class WashroomSimulation {<br><br>    public static void main(String[] args) throws Exception{<br>        Washroom washroom = new Washroom();<br><br>        Thread person1 = new Thread(new WashroomQuickTask(washroom), &quot;Person 1&quot;);<br>        Thread person2 = new Thread(new WashroomLongTask(washroom), &quot;Person 2&quot;);<br>        Thread cleaner = new Thread(new WashroomCleanTask(washroom), &quot;Cleaner&quot;);<br>        Thread person4 = new Thread(new WashroomQuickTask(washroom), &quot;Person 4&quot;);<br>        cleaner.setDaemon(true);<br><br>        person1.start();<br>        person2.start();<br>        cleaner.start();<br>        person4.start();<br>    }<br>}</pre><p>In this simulation, we set the cleaner thread as a daemon thread using cleaner.setDaemon(true). This ensures that the cleaner thread runs continuously in the background, performing its cleaning task as long as the program is running. By making it a daemon thread, we allow the JVM to exit when all non-daemon threads have finished, ensuring that the cleaner doesn&#39;t prevent the program from shutting down properly. This setup ensures the washroom is always available for use without any hanging threads waiting indefinitely.</p><p>Here is an example of the result you might see when running this code:</p><pre>Cleaner is checking if the washroom needs cleaning.<br>Person 4 is in line.<br>Person 2 is in line.<br>Person 1 is in line.<br>Cleaner - washroom is clean. Leaving the washroom.<br>Person 1 is using the washroom for quick need<br>Person 1 finished using the washroom<br>Person 2 - washroom is dirty. Waiting to use the washroom (long need)<br>Person 4 - washroom is dirty. Waiting to use the washroom (quick need)<br>Cleaner is cleaning the washroom<br>Cleaner finished cleaning the washroom. Leave the washroom.<br>Person 2 is using the washroom for long need<br>Person 2 finished using the washroom<br>Cleaner is checking if the washroom needs cleaning.<br>Cleaner is cleaning the washroom<br>Cleaner finished cleaning the washroom. Leave the washroom.<br>Person 4 is using the washroom for quick need<br>Person 4 finished using the washroom</pre><h3>Conclusion</h3><p>In this article, we’ve explored the basics of threading and synchronization in Java using a washroom example. We created specific task classes for quick needs, long needs, and cleaning, ensuring a modular and maintainable design. By using the synchronized keyword, we ensured that only one thread could access the critical section at a time, effectively managing our shared resource – the washroom. The synchronized block, along with the this reference, acted like a mutex, providing exclusive access to the washroom for one thread at a time.</p><p>We also made the cleaner task run continuously in a daemon thread to keep the washroom clean as long as the program runs, ensuring that the washroom is always available for use. This setup avoided potential issues with threads waiting indefinitely.</p><p>I encourage you to experiment with different approaches and scenarios to deepen your understanding of threading and synchronization in Java. Try adding more tasks, handling different types of resources, or exploring other synchronization mechanisms.</p><p>Happy coding!</p><p>Want to come work with us at Just Eat Takeaway.com? <a href="https://bit.ly/TechBlogFooter">Check out our open roles</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=957b157dcbf9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/justeattakeaway-tech/java-thread-management-957b157dcbf9">Effective Java Thread Management: A Fun Washroom Example</a> was originally published in <a href="https://medium.com/justeattakeaway-tech">Just Eat Takeaway-tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Virtual Threads in Java 21: Boosting Application Scalability and Performance]]></title>
            <link>https://medium.com/justeattakeaway-tech/virtual-threads-in-java-21-boosting-application-scalability-and-performance-32acc64bfaea?source=rss-6d10b4218227------2</link>
            <guid isPermaLink="false">https://medium.com/p/32acc64bfaea</guid>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[virtual-threads]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Weberton Faria]]></dc:creator>
            <pubDate>Thu, 25 Apr 2024 12:23:02 GMT</pubDate>
            <atom:updated>2024-04-25T12:23:02.031Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IfR6tJcJZT5JMbxmaHFH4w.png" /></figure><p>In the past, Java’s approach to concurrency relied heavily on OS-level threads — powerful, sure, but often heavy on resource consumption. Now, with the advent of Java 21, there’s a game-changer on the scene: Virtual Threads. Launched as part of Project Loom, this new feature is engineered to cut down the heavy lifting often associated with handling multiple tasks at once. Virtual Threads excel in managing numerous blocking IO operations, making them a perfect fit for modern applications that need both efficiency and scalability.</p><p>In this article, we’re going to dive into what Virtual Threads are, show you how to use them through practical examples and compare them to traditional threads to spotlight their benefits. This fresh take on concurrency is exactly what today’s developers need to meet the challenges of modern software development.</p><h3>Exploring Virtual Threads: The New Approach to Concurrency</h3><p>Imagine Virtual Threads as a smarter, more efficient way to manage tasks that typically slow down systems — like reading files or waiting for network data. Launched with Java 21 under Project Loom, Virtual Threads are crafted to be lightweight and are fully managed by the Java Virtual Machine (JVM). This design means they aren’t as dependent on the operating system’s resources as their traditional counterparts.</p><p>In traditional Java setups, each thread is a Platform Thread directly linked to an OS thread. This one-to-one correlation means every Java thread consumes substantial resources, potentially bogging down your system. Check out the image below for a visual breakdown of this relationship.</p><figure><img alt="Diagram of one-to-one mapping between Java Platform Threads and OS Threads." src="https://cdn-images-1.medium.com/max/911/1*adttJwN2O5Z_S9U30wrb9A.png" /><figcaption>Java Platform Thread to OS Thread Mapping</figcaption></figure><p>In contrast, Virtual Threads are managed directly by the JVM and are capable of running many threads on just a few OS threads. This efficient many-to-one relationship means that a large number of Virtual Threads can be handled with significantly fewer Platform Threads. The image below illustrates how this works in practice.</p><figure><img alt="Many-to-one mapping of multiple Virtual Threads (VT) to a single Java Platform Thread, for efficient concurrency." src="https://cdn-images-1.medium.com/max/908/1*WdzfYnnhLFPkhp4nUogtHw.png" /><figcaption>Java Virtual Threads to Platform Thread Mapping</figcaption></figure><p>Virtual Threads excel at handling tasks that involve a lot of waiting, such as I/O operations. They can be created in vast numbers without the hefty resource demands typically associated with Platform Threads. This efficiency allows applications to scale more effectively, accommodating more operations with less overhead.</p><h3>Getting Started with Virtual Threads in Java</h3><p>Integrating Virtual Threads into your Java applications is straightforward, especially with the tools that Java 21 provides. Here’s a quick guide on how to harness Virtual Threads for managing concurrent tasks effortlessly.</p><p>Java 21 introduced the Executors.newVirtualThreadPerTaskExecutor() method. This useful method creates an executor service that spawns a new Virtual Thread for each task submitted to it. This capability is particularly valuable in scenarios involving blocking I/O, where tasks need to run in parallel without weighing down the system. To see Virtual Threads in action, check out the example below:</p><pre>import java.util.concurrent.Executors;<br><br>public class VirtualThreadsExample {<br>    public static void main(String[] args) {<br><br>        try (var executorService = Executors.newVirtualThreadPerTaskExecutor()) {<br>            executorService.submit(() -&gt; System.out.println(&quot;Running on a virtual thread!&quot;));<br>        }<br>    }<br>}</pre><h3>Virtual Threads vs. Traditional Threads: A Comparative Analysis</h3><p>The example below illustrates a traditional threading scenario where a thread pool of 500 threads manages 10,000 tasks. Each task is programmed to sleep for one second. Given that the thread pool size is substantially smaller than the number of tasks, the tasks are queued and executed as threads become available. In theory, if each task executes simultaneously without any overhead, the total estimated completion time would be about 20 seconds.</p><pre>import java.time.Duration;<br>import java.util.concurrent.ExecutorService;<br>import java.util.concurrent.Executors;<br>import java.util.concurrent.atomic.AtomicInteger;<br><br>public class TraditionalThreadsExample {<br><br>    public static void main(String[] args) {<br>        AtomicInteger counter = new AtomicInteger();<br><br>        Runnable task = () -&gt; {<br>            try {<br>                Thread.sleep(Duration.ofSeconds(1));<br>            } catch (InterruptedException e) {<br>                throw new RuntimeException(e);<br>            }<br>            System.out.println(&quot;Counter &quot; + counter.incrementAndGet());<br>        };<br><br>        long startTime = System.currentTimeMillis();<br>        try (ExecutorService executorService = Executors.newFixedThreadPool(500)) {<br>            for (int i = 0; i &lt; 10_000; i++) {<br>                executorService.submit(task);<br>            }<br>        }<br><br>        long endTime = System.currentTimeMillis();<br>        System.out.println(&quot;Total execution time: &quot; + (endTime - startTime) + &quot; ms&quot;);<br>    }<br>}</pre><p>For a fun experiment, try dramatically increasing the thread pool size to something extreme, like 1 million threads. You’ll likely encounter an OutOfMemoryError as the system struggles to allocate enough resources for such a large number of threads.</p><h4>Virtual Threads Example</h4><p>Now, let’s look at how we could achieve the same with Virtual Threads.</p><pre>import java.time.Duration;<br>import java.util.concurrent.ExecutorService;<br>import java.util.concurrent.Executors;<br>import java.util.concurrent.atomic.AtomicInteger;<br><br>public class VirtualThreadExample {<br><br>    public static void main(String[] args) {<br>        AtomicInteger counter = new AtomicInteger();<br><br>        Runnable task = () -&gt; {<br>            try {<br>                Thread.sleep(Duration.ofSeconds(1));<br>            } catch (InterruptedException e) {<br>                throw new RuntimeException(e);<br>            }<br><br>            System.out.println(&quot;Counter &quot; + counter.incrementAndGet());<br>        };<br><br>        long startTime = System.currentTimeMillis();<br>        try (ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor()) {<br>            for (int i = 0; i &lt; 10_000; i++) {<br>                executorService.submit(task);<br>            }<br>        }<br><br>        long endTime = System.currentTimeMillis();<br>        System.out.println(&quot;Total execution time: &quot; + (endTime - startTime) + &quot; ms&quot;);<br>    }<br>}</pre><p>In this example, we’re leveraging Java’s Executors.newVirtualThreadPerTaskExecutor() to manage 10,000 tasks, with each task taking a brief pause for one second. This method is a boon for such heavy-duty tasks, as it avoids the need for a large thread pool and sidesteps the risk of running out of memory—common issues with fixed thread pools.</p><p>Because Virtual Threads are so lightweight, the total execution time will generally be just slightly longer than the duration of the longest task, with a bit of extra time for minor overhead. Give this code a try; you’ll likely see it complete in just <strong>over one second</strong>. All tasks run almost in parallel, without the heavy resource drain typically associated with traditional threading models.</p><h3>Wrapping Up: The Future of Concurrency with Virtual Threads</h3><p>The introduction of Virtual Threads in Java 21 is a significant step forward for developers looking to build efficient and scalable applications. These nimble threads handle concurrency effortlessly, especially for tasks heavy on I/O, liberating developers from the constraints of traditional thread management. By adopting Virtual Threads, you gain smoother scalability and more straightforward code, empowering you to manage vast numbers of tasks with ease.</p><p>As Java continues to advance, Virtual Threads are emerging as an essential tool for the modern developer, paving the way toward a simpler, more effective future in concurrent programming. Try integrating Virtual Threads into your projects and experience the transformative impact they can have on your Java applications!</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32acc64bfaea" width="1" height="1" alt=""><hr><p><a href="https://medium.com/justeattakeaway-tech/virtual-threads-in-java-21-boosting-application-scalability-and-performance-32acc64bfaea">Virtual Threads in Java 21: Boosting Application Scalability and Performance</a> was originally published in <a href="https://medium.com/justeattakeaway-tech">Just Eat Takeaway-tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an LRU Cache in Java: A Simple Approach Using LinkedHashMap]]></title>
            <link>https://medium.com/justeattakeaway-tech/building-an-lru-cache-in-java-a-simple-approach-using-linkedhashmap-7e984b223cdf?source=rss-6d10b4218227------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e984b223cdf</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[linkedhashmap]]></category>
            <category><![CDATA[lru-cache]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Weberton Faria]]></dc:creator>
            <pubDate>Thu, 28 Mar 2024 15:52:48 GMT</pubDate>
            <atom:updated>2024-03-28T15:52:48.840Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*nD5fyFrBkTJJTIMJqd4kHA.png" /></figure><h3>Introduction</h3><p>In the world of software development, efficient management of resources is key to building high-performance applications. A fundamental technique in this domain is implementing a Least Recently Used (LRU) cache. Such caches are crucial in optimizing data retrieval processes and managing memory efficiently, especially in resource-constrained environments.</p><p>In this article, we’re going to walk through how to construct an LRU cache in Java, using the versatile LinkedHashMapclass.</p><p>Let’s dive in and unpack this essential technique.</p><h3>What is a Cache?</h3><p>A cache is a special kind of memory that stores data for a short time. It’s really fast, and its main job is to make accessing data quicker than usual. This is important because it helps avoid slow processes that happen when a computer reads or writes data.</p><p>Caching is a big deal in making computers work faster. It’s used in lots of different areas, like making websites load quickly or helping apps on your phone run smoothly. By using caching, we can make sure computers do their jobs more efficiently.</p><h3>What is LRU Cache?</h3><p>LRU stands for ‘Least Recently Used,’ and it’s a smart way of managing cache memory. Imagine a cache as a small box where you can only fit a limited number of items. When it gets full and you need to put something new in, LRU helps by removing the item that hasn’t been used for the longest time. This method works great in situations where you’re less likely to need old data again.</p><p>Let’s take an example: think about a website that recommends products to you. To suggest items you might like, it needs to quickly look at what you’ve recently viewed or bought. But with so many products and users, it’s impossible to store all this information in the main memory — it’s just too much.</p><p>Here’s where an LRU cache comes in handy. It keeps track of the products you’ve looked at or bought most recently. So, as you move around on the website, it can quickly use this cache to suggest other items you might like, making the whole experience faster and more personal.</p><h3>How to Build an LRU Cache in Practice</h3><p>The LRU Cache can be implemented using a doubly linked list combined with a HashMap. However, in Java, this implementation can be abstracted using the LinkedHashMapclass. Internally, LinkedHashMapimplements a doubly linked list to maintain the order of elements and a HashMapto store keys and values, thereby enabling quick access to elements.</p><h4>Java Implementation Using LinkedHashMap</h4><pre>import java.util.LinkedHashMap;<br>import java.util.Map;<br><br>public class LRUCache&lt;K, V&gt; extends LinkedHashMap&lt;K, V&gt; {<br>    private final int capacity;<br><br>    public LRUCache(int capacity) {<br>        super(capacity, 0.75f, true);<br>        this.capacity = capacity;<br>    }<br><br>    @Override<br>    protected boolean removeEldestEntry(Map.Entry&lt;K, V&gt; eldest) {<br>        return size() &gt; this.capacity;<br>    }<br>}</pre><h4>Breaking Down the LRU Cache Code</h4><p>The LRUCache class takes advantage of a built-in data structure in Java, the LinkedHashMap. This structure is pretty handy because it can keep track of the order of elements based on either when they were added (insertion order) or when they were last accessed (access order). For our LRU Cache, maintaining the access order is crucial. This means every time an item is read or written, it gets moved to the end of the list.</p><p>When we set up our LRUCache class, we start by calling the constructor of LinkedHashMapwith three important parameters: initial capacity, load factor, and access order.</p><ul><li><strong>Initial Capacity</strong>: This is all about how big our cache can be. Once the cache hits this limit, it needs to remove the least recently used item before any new ones can be added.</li><li><strong>Load Factor</strong>: Think of this as a threshold that tells us how full the HashMap can get before it needs to grow bigger. We’ll set ours to 75%, which means when it’s 75% full, it’ll expand. But in our LRU Cache, we’re actually going to remove the least used items before this happens.</li><li><strong>Access Order</strong>: A simple true/false setting. We set this to true because we want to keep things in order based on how recently they’ve been accessed, not when they were put in.</li></ul><p>There’s also a crucial bit where we override the removeEldestEntry method from LinkedHashMap. This method gets called every time we add something new with putor putAll. It decides if the oldest entry (the least recently used one) should be tossed out. Our logic here is straightforward: if our map’s size is bigger than our set capacity, the oldest entry gets removed. This is the heart of the LRU Eviction process.</p><h4>Using the LRUCache Class: A Practical Example</h4><pre>    public static void main(String[] args) {<br>        LRUCache&lt;Integer, Integer&gt; cache = new LRUCache&lt;&gt;(2);<br><br>        cache.put(1, 1);<br>        cache.put(2, 2);<br>        System.out.println(cache); //output {1=1, 2=2}<br>        cache.get(1);    // returns 1<br>        System.out.println(cache); //output {2=2, 1=1}<br>        cache.put(3, 3); // Remove 2 and add 3<br>        System.out.println(cache); //output {1=1, 3=3}<br>        cache.get(2);    // return null<br>        cache.put(4, 4); // Remove 1 and add o 4<br>        System.out.println(cache); //output {3=3, 4=4}<br>        cache.get(3);    // return 3<br>        System.out.println(cache); //output {4=4, 3=3}<br>        cache.get(4);    // return 4<br>        System.out.println(cache); //output {3=3, 4=4}<br>    }</pre><h3>Conclusion</h3><p>In this article, we’ve explored how an LRU Cache can dramatically speed up data access in applications where quick responses are critical. Using Java’s LinkedHashMap to implement this algorithm offers a great mix of simplicity and effectiveness. Hopefully, you now have a clearer understanding of the LRU Cache and feel ready to apply this technique to improve your applications.</p><p>Happy coding!</p><p>—</p><p>Just Eat Takeaway.com is hiring! Want to come work with us? <a href="https://bit.ly/TechBlogFooter">Apply today</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e984b223cdf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/justeattakeaway-tech/building-an-lru-cache-in-java-a-simple-approach-using-linkedhashmap-7e984b223cdf">Building an LRU Cache in Java: A Simple Approach Using LinkedHashMap</a> was originally published in <a href="https://medium.com/justeattakeaway-tech">Just Eat Takeaway-tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring the New Horizons of Java 21: Record Patterns and Pattern Matching]]></title>
            <link>https://medium.com/justeattakeaway-tech/exploring-the-new-horizons-of-java-21-record-patterns-and-patterning-matches-cb482ce5db40?source=rss-6d10b4218227------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb482ce5db40</guid>
            <category><![CDATA[java-21-features]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java-records]]></category>
            <category><![CDATA[sealed-classes]]></category>
            <dc:creator><![CDATA[Weberton Faria]]></dc:creator>
            <pubDate>Fri, 16 Feb 2024 18:49:50 GMT</pubDate>
            <atom:updated>2024-03-18T16:01:23.070Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*xf0U2vJRDybVR5IupbPBdQ.png" /></figure><h3>Introduction</h3><p>Java is constantly evolving, and with each update, it brings new and exciting features. Today, we’re diving into Java 21, a significant leap forward in its ongoing innovation journey with the introduction of Record Patterns and Pattern Matching. These new features make our lives as developers simpler and our code cleaner and more intuitive. So, let’s embark on this journey together to demystify Record Patterns and Patterning Matches and see how they can add a new dimension to your Java projects.</p><h3>Introduction to Records in Java</h3><p>Records, introduced in Java 16, are a type of class in Java. They provide a compact syntax to declare classes that are transparent holders for shallowly immutable data.</p><p>For instance, a Person record could be defined as:</p><pre>public record Person(String name, int age) {}</pre><p>They have a concise syntax and automatically implement data-handling methods like equals(), hashCode(), and toString(), and enforce immutability, which leads to more predictable and less error-prone code.</p><h4>The Basics of Pattern Matching in Java</h4><p>Pattern matching simplifies the process of checking and extracting data from objects. It was enhanced in Java with the introduction of the instanceof operator.</p><p>Consider a sealed interface Employee and two record types FullTimeEmployee and Freelancer:</p><pre>public sealed interface Employee permits FullTimeEmployee, Freelancer {<br>    String getName();<br>    String getDepartment();<br>}</pre><pre>public record FullTimeEmployee(String name, String department, double salary) implements Employee {<br>  ...<br>}</pre><pre>public record Freelancer(String name, String department, double hourlyRate) implements Employee {<br>  ...<br>}</pre><p>In this setup, Employee is a sealed interface, meaning only the specified records (FullTimeEmployee and Freelancer) can implement it. This allows more controlled and predictable type hierarchies.</p><h4>Using Pattern Matching with Sealed Types</h4><p>Pattern matching can be particularly powerful when working with sealed types. For example:</p><pre>public void processEmployee(Employee employee) {<br>    if (employee instanceof FullTimeEmployee fte) {<br>        // Process full-time employee<br>    } else if (employee instanceof Freelancer freelancer) {<br>        // Process freelancer<br>    }<br>}</pre><p>This approach eliminates the need for explicit casting, as the type of employee is automatically checked and cast to the respective types (FullTimeEmployee or Freelancer), simplifying the code and reducing potential errors.</p><h3>Record Patterns in Java 21</h3><p>Record Patterns, introduced in Java 21, represent a significant advancement in pattern matching. They allow for the deconstruction of record objects in a pattern match, enabling developers to directly extract and use the components of a record.</p><p>This feature simplifies code by eliminating the need for boilerplate extraction of record components. It enhances readability and makes the code more concise and expressive.</p><h4>Example of Record Patterns</h4><p>Consider the Employee, FullTimeEmployee, and Freelancer records from our previous example. With <a href="https://docs.oracle.com/en/java/javase/21/language/record-patterns.html#GUID-7623D3AD-4141-4914-A384-60C65BD0C010">Record Patterns</a>, you can deconstruct these records directly in a pattern match:</p><pre>public void displayEmployeeInfo(Employee employee) {<br>    if (employee instanceof FullTimeEmployee(String name, String department, double salary)) {<br>        System.out.println(name + &quot; works in &quot; + department + &quot; with a salary of &quot; + salary);<br>    } else if (employee instanceof Freelancer(String name, String department, double hourlyRate)) {<br>        System.out.println(name + &quot; works in &quot; + department + &quot; as a freelancer with an hourly rate of &quot; + hourlyRate);<br>    }<br>}</pre><p>In this code, the instanceof check is combined with a pattern that deconstructs the record, directly extracting the name, department, and salary or hourlyRate, depending on the record type.</p><h3>Patterning Matches</h3><p><a href="https://docs.oracle.com/en/java/javase/21/language/pattern-matching-switch-expressions-and-statements.html#GUID-E69EEA63-E204-41B4-AA7F-D58B26A3B232">Patterning Matches</a> in Java 21 further extend the capabilities of pattern matching. This feature allows patterns to be used in more places, such as switch expressions and statements, enhancing the flexibility and power of pattern matching in Java.</p><p>This addition enables more expressive and versatile code structures, allowing for cleaner and more intuitive conditional logic based on object types and their states.</p><h4>Example of Patterning Matches</h4><pre>public String getEmployeeDetails(Employee employee) {<br>    return switch (employee) {<br>        case FullTimeEmployee(String name, _, double salary) -&gt; <br>            name + &quot; is a full-time employee with a salary of &quot; + salary;<br>        case Freelancer(String name, _, double hourlyRate) -&gt; <br>            name + &quot; is a freelancer with an hourly rate of &quot; + hourlyRate;<br>    };<br>}</pre><p>You&#39;ll notice that the switch statement doesn&#39;t require a default case. This is because we&#39;re using a sealed interface for the Employee type. Since Employee is sealed and permits only FullTimeEmployee and Freelancer, the compiler can ensure that all possible subtypes are covered in the switch. This eliminates the need for a default case, making our code more concise and type-safe.</p><p>This section has introduced and explained the concepts of Record Patterns and Patterning Matches in Java 21, using the Employee hierarchy as a practical example. These features significantly simplify and enhance the way developers interact with records and utilize pattern matching.</p><h4>Unnamed variables</h4><p>Java 21 also introduces pattern matching with <em>unnamed variables</em>, represented by an underscore (_), adding further convenience and streamlining code. It&#39;s important to note that while Record Patterns and Patterning Matches are standard features in Java 21, the use of unnamed variables in pattern matching is still in the preview phase. Therefore, to experiment with unnamed variables, you need to run your Java application with the --enable-preview flag.</p><h3>Conclusion</h3><p>The journey of Java continues to be one of evolution and adaptation. With each release, Java cements its position as a robust, versatile language, capable of meeting the ever-changing demands of modern software development. Record Patterns and Patterning Matches in Java 21 are a testament to this ongoing evolution, offering developers powerful tools to keep their codebase clean and their programming practices ahead of the curve.</p><p>As we conclude, I encourage you to dive into these new features. Experiment with them in your projects, discover their potential, and see how they can transform your Java coding experience. Remember, the landscape of Java is dynamic and ever-evolving, and staying abreast of these changes is key to being an effective Java developer.</p><p>For those eager to learn more, seek out further resources, join Java forums, and engage with the community. Your journey with Java 21 is just beginning, and the possibilities are as exciting as they are limitless.</p><p>Happy coding!</p><p>—</p><p>Just Eat Takeaway.com is hiring! Want to come work with us? <a href="https://bit.ly/TechBlogFooter">Apply today</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb482ce5db40" width="1" height="1" alt=""><hr><p><a href="https://medium.com/justeattakeaway-tech/exploring-the-new-horizons-of-java-21-record-patterns-and-patterning-matches-cb482ce5db40">Exploring the New Horizons of Java 21: Record Patterns and Pattern Matching</a> was originally published in <a href="https://medium.com/justeattakeaway-tech">Just Eat Takeaway-tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>