<?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 Tadeo Aragón on Medium]]></title>
        <description><![CDATA[Stories by Tadeo Aragón on Medium]]></description>
        <link>https://medium.com/@tadeoaragoon?source=rss-e126e053b725------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*P15ozr0QyhWfeVoTqlH3lg.png</url>
            <title>Stories by Tadeo Aragón on Medium</title>
            <link>https://medium.com/@tadeoaragoon?source=rss-e126e053b725------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 04:52:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tadeoaragoon/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[The Illusion That AI Has Replaced Programmers]]></title>
            <link>https://medium.com/@tadeoaragoon/the-illusion-that-ai-has-replaced-programmers-5adbf7f838b7?source=rss-e126e053b725------2</link>
            <guid isPermaLink="false">https://medium.com/p/5adbf7f838b7</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[humanity]]></category>
            <dc:creator><![CDATA[Tadeo Aragón]]></dc:creator>
            <pubDate>Thu, 22 Jan 2026 21:23:40 GMT</pubDate>
            <atom:updated>2026-01-22T21:23:40.752Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UR30dsVkJ9BsFtjHV8ehYg.png" /></figure><p>I’ve been working with AI tools such as Claude, Gemini, and ChatGPT for a relatively short period of time. Through daily use, I began noticing recurring issues and patterns that became impossible to ignore. After reflecting on them, I decided to write about what I’ve observed.</p><blockquote>There is a growing belief that AI has replaced programmers.<br> The reality is quite the opposite.</blockquote><p>Today, software development is not easier — it is heavier, more complex, and comes with greater responsibility. At the same time, salaries are becoming harder to justify, largely due to a deliberately cultivated perception that AI “does everything” on its own.</p><p>AI can write code. But someone still has to:</p><ul><li>Review and validate that code</li><li>Understand the programming language and the full stack</li><li>Identify edge cases, logical flaws, and silent failures</li><li>Catch recurring mistakes AI consistently makes</li></ul><p>The core issue is simple:<br> AI has no structural memory of a system — only temporary context.It can perform well locally, solving isolated problems. At a global system level, however, it often produces code that breaks other modules and violates implicit assumptions.</p><p>AI also tends to over-engineer solutions:</p><ul><li>Too many layers</li><li>Unnecessary abstractions</li><li>More code than required</li></ul><p>Not because it is intelligent, but because it lacks human judgment and intuition. AI is not true intelligence — it is extremely well-organized information.</p><p>And in production?</p><p>Very few AI-generated systems work perfectly on the first deployment.<br> Even when they appear to work, hidden bugs surface later due to multiple overlapping contexts that AI cannot fully reason about.</p><p>Leaving tools like Claude or Gemini coding autonomously:</p><ul><li>Burns tokens aggressively</li><li>Rewrites code without restraint</li><li>Increases operational costs</li></ul><p>The conclusion is straightforward:<br> Hiring a skilled programmer and giving them AI is far more efficient than delegating full responsibility to AI alone. Because when production fails, AI is never held accountable. A human always is.</p><p>Artificial intelligence is not something that destroys or eliminates jobs.<br> It is a tool designed to accelerate and optimize human work — not to replace judgment, experience, or accountability.</p><p>And beyond algorithm refinement and optimization, it’s important to be honest: reaching true Artificial General Intelligence will require fundamentally new knowledge and new hardware. AGI will not emerge simply by polishing current models — it demands a genuine technological leap. Humanity is still far from achieving that goal.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5adbf7f838b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Virtual Threads in Java 21: The Threading Revolution You’ve Been Waiting For]]></title>
            <link>https://medium.com/@tadeoaragoon/virtual-threads-in-java-21-the-threading-revolution-youve-been-waiting-for-40e74ed94468?source=rss-e126e053b725------2</link>
            <guid isPermaLink="false">https://medium.com/p/40e74ed94468</guid>
            <category><![CDATA[virtual-threads]]></category>
            <category><![CDATA[java-21-features]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[patterns]]></category>
            <dc:creator><![CDATA[Tadeo Aragón]]></dc:creator>
            <pubDate>Sat, 23 Aug 2025 04:20:53 GMT</pubDate>
            <atom:updated>2025-08-23T04:20:53.704Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LbrxWQW-EceRoWE0J9xOJg.png" /></figure><p>After 7 years of Java development, I’ve seen countless attempts to make concurrent programming easier and more scalable. From the early days of Thread and Runnable to the complexity of CompletableFuture and reactive streams, we&#39;ve always struggled with the fundamental tension between simplicity and performance in concurrent applications.</p><p>Virtual Threads in Java 21 finally breaks this trade-off. They represent the most significant advancement in Java concurrency since the introduction of the java.util.concurrent package in Java 5.</p><h3>The Million-Thread Problem We All Know</h3><p>Let’s start with a scenario that every server-side Java developer has encountered. You’re building a web service that needs to handle thousands of concurrent requests, each involving I/O operations like database queries or HTTP calls:</p><pre>// Traditional approach - Platform threads<br>public class TraditionalThreadingService {<br>    private final ExecutorService executor = Executors.newFixedThreadPool(200);<br>    <br>    public void handleRequest(String requestId) {<br>        executor.submit(() -&gt; {<br>            try {<br>                // Simulate database call<br>                String userData = fetchUserFromDatabase(requestId);<br>                <br>                // Simulate external API call<br>                String enrichedData = callExternalService(userData);<br>                <br>                // Process and respond<br>                processAndRespond(requestId, enrichedData);<br>                <br>            } catch (Exception e) {<br>                handleError(requestId, e);<br>            }<br>        });<br>    }<br>    <br>    private String fetchUserFromDatabase(String requestId) {<br>        // This blocks the platform thread for 50ms<br>        simulateIoOperation(50);<br>        return &quot;User data for &quot; + requestId;<br>    }<br>    <br>    private String callExternalService(String userData) {<br>        // This blocks the platform thread for 100ms<br>        simulateIoOperation(100);<br>        return &quot;Enriched: &quot; + userData;<br>    }<br>    <br>    private void simulateIoOperation(long millis) {<br>        try {<br>            Thread.sleep(millis);<br>        } catch (InterruptedException e) {<br>            Thread.currentThread().interrupt();<br>        }<br>    }<br>}</pre><p><strong>The Problem:</strong> Each platform thread consumes ~2MB of memory and is mapped 1:1 to an OS thread. With 200 threads, you’re using 400MB just for thread stacks, and you’re limited by OS thread limits (typically 1000–4000 threads per process).</p><p><strong>The Consequence:</strong> Your application can handle at most 200 concurrent requests, even though 99% of the time, threads are just waiting for I/O operations to complete.</p><h3>Enter Virtual Threads: The Game Changer</h3><p>Virtual threads are lightweight threads managed entirely by the JVM. They’re not mapped 1:1 to OS threads. Instead, the JVM multiplexes millions of virtual threads onto a small number of OS threads (carrier threads).</p><p>Here’s the same service reimplemented with virtual threads:</p><pre>// Virtual threads approach<br>public class VirtualThreadService {<br>    <br>    public void handleRequest(String requestId) {<br>        // Create and start a virtual thread - no thread pool needed!<br>        Thread.ofVirtual().start(() -&gt; {<br>            try {<br>                // Same business logic - but now truly scalable<br>                String userData = fetchUserFromDatabase(requestId);<br>                String enrichedData = callExternalService(userData);<br>                processAndRespond(requestId, enrichedData);<br>                <br>            } catch (Exception e) {<br>                handleError(requestId, e);<br>            }<br>        });<br>    }<br>    <br>    // Same I/O operations - but now they don&#39;t waste OS threads<br>    private String fetchUserFromDatabase(String requestId) {<br>        simulateIoOperation(50);<br>        return &quot;User data for &quot; + requestId;<br>    }<br>    <br>    private String callExternalService(String userData) {<br>        simulateIoOperation(100);<br>        return &quot;Enriched: &quot; + userData;<br>    }<br>}</pre><p><strong>The Magic:</strong> You can now handle millions of concurrent requests with the same memory footprint and simpler code!</p><h4>Understanding Virtual Threads Architecture</h4><p>Let me explain how virtual threads achieve this magic:</p><h4>Platform Threads vs Virtual Threads</h4><pre>public class ThreadComparisonDemo {<br>    public static void main(String[] args) {<br>        demonstratePlatformThreads();<br>        demonstrateVirtualThreads();<br>    }<br>    <br>    private static void demonstratePlatformThreads() {<br>        System.out.println(&quot;=== Platform Threads Demo ===&quot;);<br>        long startTime = System.currentTimeMillis();<br>        <br>        try (var executor = Executors.newFixedThreadPool(1000)) {<br>            for (int i = 0; i &lt; 10000; i++) {<br>                final int taskId = i;<br>                executor.submit(() -&gt; {<br>                    try {<br>                        Thread.sleep(1000); // Simulate I/O<br>                        if (taskId % 1000 == 0) {<br>                            System.out.println(&quot;Platform thread task &quot; + taskId + <br>                                &quot; running on: &quot; + Thread.currentThread());<br>                        }<br>                    } catch (InterruptedException e) {<br>                        Thread.currentThread().interrupt();<br>                    }<br>                });<br>            }<br>        }<br>        <br>        long endTime = System.currentTimeMillis();<br>        System.out.println(&quot;Platform threads completed in: &quot; + (endTime - startTime) + &quot;ms&quot;);<br>    }<br>    <br>    private static void demonstrateVirtualThreads() {<br>        System.out.println(&quot;\n=== Virtual Threads Demo ===&quot;);<br>        long startTime = System.currentTimeMillis();<br>        <br>        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {<br>            for (int i = 0; i &lt; 10000; i++) {<br>                final int taskId = i;<br>                executor.submit(() -&gt; {<br>                    try {<br>                        Thread.sleep(1000); // Same I/O simulation<br>                        if (taskId % 1000 == 0) {<br>                            System.out.println(&quot;Virtual thread task &quot; + taskId + <br>                                &quot; running on: &quot; + Thread.currentThread());<br>                        }<br>                    } catch (InterruptedException e) {<br>                        Thread.currentThread().interrupt();<br>                    }<br>                });<br>            }<br>        }<br>        <br>        long endTime = System.currentTimeMillis();<br>        System.out.println(&quot;Virtual threads completed in: &quot; + (endTime - startTime) + &quot;ms&quot;);<br>    }<br>}</pre><p><strong>Key Observation:</strong> Virtual threads show carrier thread names like VirtualThread[#21]/runnable@ForkJoinPool-1-worker-1, indicating they&#39;re multiplexed onto a small pool of carrier threads.</p><h3>Creating and Managing Virtual Threads</h3><p>Java 21 provides several ways to create virtual threads:</p><h4>1. Thread.ofVirtual() — The Builder Pattern</h4><pre>public class VirtualThreadCreationExamples {<br>    <br>    public void demonstrateBuilderPattern() {<br>        // Basic virtual thread<br>        Thread vt1 = Thread.ofVirtual()<br>            .start(() -&gt; System.out.println(&quot;Hello from virtual thread!&quot;));<br>        <br>        // Named virtual thread<br>        Thread vt2 = Thread.ofVirtual()<br>            .name(&quot;data-processor&quot;)<br>            .start(() -&gt; processData());<br>        <br>        // Virtual thread with custom uncaught exception handler<br>        Thread vt3 = Thread.ofVirtual()<br>            .name(&quot;error-prone-task&quot;)<br>            .uncaughtExceptionHandler((thread, exception) -&gt; {<br>                System.err.println(&quot;Virtual thread &quot; + thread.getName() + <br>                    &quot; failed: &quot; + exception.getMessage());<br>            })<br>            .start(() -&gt; {<br>                throw new RuntimeException(&quot;Simulated error&quot;);<br>            });<br>        <br>        // Wait for completion<br>        try {<br>            vt1.join();<br>            vt2.join();<br>            vt3.join();<br>        } catch (InterruptedException e) {<br>            Thread.currentThread().interrupt();<br>        }<br>    }<br>    <br>    private void processData() {<br>        System.out.println(&quot;Processing data on: &quot; + Thread.currentThread());<br>        try {<br>            Thread.sleep(1000); // Simulated work<br>        } catch (InterruptedException e) {<br>            Thread.currentThread().interrupt();<br>        }<br>    }<br>}</pre><h4><strong>2. Virtual Thread Executors</strong></h4><pre>public class VirtualThreadExecutors {<br>    <br>    public void demonstrateExecutors() {<br>        // One virtual thread per task - unlimited concurrency<br>        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {<br>            <br>            List&lt;Future&lt;String&gt;&gt; futures = new ArrayList&lt;&gt;();<br>            <br>            // Submit 100,000 tasks - no problem!<br>            for (int i = 0; i &lt; 100000; i++) {<br>                final int taskId = i;<br>                Future&lt;String&gt; future = executor.submit(() -&gt; {<br>                    // Simulate different types of I/O operations<br>                    simulateRandomIoOperation();<br>                    return &quot;Task &quot; + taskId + &quot; completed by &quot; + <br>                           Thread.currentThread().getName();<br>                });<br>                futures.add(future);<br>            }<br>            <br>            // Collect results<br>            int completed = 0;<br>            for (Future&lt;String&gt; future : futures) {<br>                try {<br>                    String result = future.get();<br>                    completed++;<br>                    if (completed % 10000 == 0) {<br>                        System.out.println(&quot;Completed &quot; + completed + &quot; tasks&quot;);<br>                    }<br>                } catch (ExecutionException | InterruptedException e) {<br>                    System.err.println(&quot;Task failed: &quot; + e.getMessage());<br>                }<br>            }<br>            <br>            System.out.println(&quot;All &quot; + completed + &quot; tasks completed!&quot;);<br>        }<br>    }<br>    <br>    private void simulateRandomIoOperation() {<br>        try {<br>            // Random I/O delay between 10-500ms<br>            long delay = 10 + (long)(Math.random() * 490);<br>            Thread.sleep(delay);<br>        } catch (InterruptedException e) {<br>            Thread.currentThread().interrupt();<br>        }<br>    }<br>}</pre><h4>3. Virtual Thread Factories</h4><pre>public class VirtualThreadFactories {<br>    <br>    public void demonstrateFactories() {<br>        // Custom thread factory for virtual threads<br>        ThreadFactory virtualThreadFactory = Thread.ofVirtual()<br>            .name(&quot;worker-&quot;, 1)<br>            .factory();<br>        <br>        // Use with standard executors<br>        try (var executor = Executors.newThreadPerTaskExecutor(virtualThreadFactory)) {<br>            for (int i = 0; i &lt; 10; i++) {<br>                executor.submit(() -&gt; {<br>                    System.out.println(&quot;Working on: &quot; + Thread.currentThread().getName());<br>                    try {<br>                        Thread.sleep(1000);<br>                    } catch (InterruptedException e) {<br>                        Thread.currentThread().interrupt();<br>                    }<br>                });<br>            }<br>        }<br>    }<br>}</pre><h3>Real-World Example: High-Throughput Web Scraper</h3><p>Let’s build a practical example that showcases virtual threads’ power — a web scraper that can handle thousands of concurrent HTTP requests:</p><pre>public class VirtualThreadWebScraper {<br>    private final HttpClient httpClient;<br>    <br>    public VirtualThreadWebScraper() {<br>        this.httpClient = HttpClient.newBuilder()<br>            .connectTimeout(Duration.ofSeconds(10))<br>            .build();<br>    }<br>    <br>    public void scrapeUrls(List&lt;String&gt; urls) {<br>        System.out.println(&quot;Scraping &quot; + urls.size() + &quot; URLs with virtual threads...&quot;);<br>        <br>        long startTime = System.currentTimeMillis();<br>        <br>        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {<br>            // Submit all scraping tasks<br>            List&lt;Future&lt;ScrapeResult&gt;&gt; futures = urls.stream()<br>                .map(url -&gt; executor.submit(() -&gt; scrapeUrl(url)))<br>                .toList();<br>            <br>            // Collect results as they complete<br>            List&lt;ScrapeResult&gt; results = new ArrayList&lt;&gt;();<br>            int successful = 0;<br>            int failed = 0;<br>            <br>            for (Future&lt;ScrapeResult&gt; future : futures) {<br>                try {<br>                    ScrapeResult result = future.get();<br>                    results.add(result);<br>                    <br>                    if (result.success()) {<br>                        successful++;<br>                    } else {<br>                        failed++;<br>                    }<br>                    <br>                    // Progress reporting<br>                    int total = successful + failed;<br>                    if (total % 100 == 0) {<br>                        System.out.printf(&quot;Progress: %d/%d (Success: %d, Failed: %d)%n&quot;,<br>                            total, urls.size(), successful, failed);<br>                    }<br>                    <br>                } catch (ExecutionException | InterruptedException e) {<br>                    failed++;<br>                    System.err.println(&quot;Task execution failed: &quot; + e.getMessage());<br>                }<br>            }<br>            <br>            long endTime = System.currentTimeMillis();<br>            long duration = endTime - startTime;<br>            <br>            // Final statistics<br>            System.out.printf(&quot;%nScraping completed in %d ms%n&quot;, duration);<br>            System.out.printf(&quot;Total: %d, Successful: %d, Failed: %d%n&quot;, <br>                urls.size(), successful, failed);<br>            System.out.printf(&quot;Throughput: %.2f requests/second%n&quot;, <br>                (urls.size() * 1000.0) / duration);<br>            <br>            // Show some sample results<br>            results.stream()<br>                .filter(ScrapeResult::success)<br>                .limit(5)<br>                .forEach(result -&gt; <br>                    System.out.printf(&quot;✓ %s (%d chars, %d ms)%n&quot;, <br>                        result.url(), result.contentLength(), result.responseTime()));<br>        }<br>    }<br>    <br>    private ScrapeResult scrapeUrl(String url) {<br>        long startTime = System.currentTimeMillis();<br>        <br>        try {<br>            HttpRequest request = HttpRequest.newBuilder()<br>                .uri(URI.create(url))<br>                .timeout(Duration.ofSeconds(30))<br>                .build();<br>            <br>            HttpResponse&lt;String&gt; response = httpClient.send(request, <br>                HttpResponse.BodyHandlers.ofString());<br>            <br>            long responseTime = System.currentTimeMillis() - startTime;<br>            <br>            return new ScrapeResult(<br>                url,<br>                true,<br>                response.statusCode(),<br>                response.body().length(),<br>                responseTime,<br>                null<br>            );<br>            <br>        } catch (Exception e) {<br>            long responseTime = System.currentTimeMillis() - startTime;<br>            return new ScrapeResult(<br>                url,<br>                false,<br>                -1,<br>                0,<br>                responseTime,<br>                e.getMessage()<br>            );<br>        }<br>    }<br>    <br>    // Record to hold scraping results<br>    public record ScrapeResult(<br>        String url,<br>        boolean success,<br>        int statusCode,<br>        int contentLength,<br>        long responseTime,<br>        String error<br>    ) {}<br>    <br>    // Demo method<br>    public static void main(String[] args) {<br>        // Generate sample URLs for testing<br>        List&lt;String&gt; urls = generateSampleUrls(1000);<br>        <br>        VirtualThreadWebScraper scraper = new VirtualThreadWebScraper();<br>        scraper.scrapeUrls(urls);<br>    }<br>    <br>    private static List&lt;String&gt; generateSampleUrls(int count) {<br>        // In a real scenario, you&#39;d read these from a file or database<br>        List&lt;String&gt; baseUrls = List.of(<br>            &quot;https://httpbin.org/delay/1&quot;,<br>            &quot;https://httpbin.org/delay/2&quot;,<br>            &quot;https://httpbin.org/status/200&quot;,<br>            &quot;https://httpbin.org/json&quot;,<br>            &quot;https://httpbin.org/uuid&quot;<br>        );<br>        <br>        List&lt;String&gt; urls = new ArrayList&lt;&gt;();<br>        for (int i = 0; i &lt; count; i++) {<br>            urls.add(baseUrls.get(i % baseUrls.size()));<br>        }<br>        return urls;<br>    }<br>}</pre><p><strong>Performance Impact:</strong> This scraper can handle 10,000+ concurrent requests with minimal memory overhead, something that would require careful tuning and significant resources with platform threads.</p><h3>Virtual Threads vs Async Programming</h3><p>One of the biggest advantages of virtual threads is eliminating the need for complex async programming patterns:</p><pre>// Complex async approach with CompletableFuture<br>public class AsyncApproach {<br>    private final HttpClient client = HttpClient.newHttpClient();<br>    <br>    public CompletableFuture&lt;String&gt; processUserDataAsync(String userId) {<br>        return fetchUserAsync(userId)<br>            .thenCompose(user -&gt; enrichUserDataAsync(user))<br>            .thenCompose(enrichedUser -&gt; saveUserAsync(enrichedUser))<br>            .thenApply(savedUser -&gt; &quot;Processing complete for &quot; + savedUser.id())<br>            .exceptionally(throwable -&gt; &quot;Error processing user: &quot; + throwable.getMessage());<br>    }<br>    <br>    private CompletableFuture&lt;User&gt; fetchUserAsync(String userId) {<br>        return CompletableFuture.supplyAsync(() -&gt; {<br>            // Simulate database call<br>            simulateIoOperation(50);<br>            return new User(userId, &quot;User Name&quot;);<br>        });<br>    }<br>    <br>    private CompletableFuture&lt;EnrichedUser&gt; enrichUserDataAsync(User user) {<br>        return CompletableFuture.supplyAsync(() -&gt; {<br>            // Simulate external API call<br>            simulateIoOperation(100);<br>            return new EnrichedUser(user.id(), user.name(), &quot;Additional data&quot;);<br>        });<br>    }<br>    <br>    private CompletableFuture&lt;EnrichedUser&gt; saveUserAsync(EnrichedUser user) {<br>        return CompletableFuture.supplyAsync(() -&gt; {<br>            // Simulate database save<br>            simulateIoOperation(30);<br>            return user;<br>        });<br>    }<br>}<br><br>// Simple synchronous approach with Virtual Threads<br>public class VirtualThreadApproach {<br>    <br>    public String processUserData(String userId) {<br>        try {<br>            User user = fetchUser(userId);<br>            EnrichedUser enrichedUser = enrichUserData(user);<br>            EnrichedUser savedUser = saveUser(enrichedUser);<br>            return &quot;Processing complete for &quot; + savedUser.id();<br>        } catch (Exception e) {<br>            return &quot;Error processing user: &quot; + e.getMessage();<br>        }<br>    }<br>    <br>    private User fetchUser(String userId) {<br>        simulateIoOperation(50);<br>        return new User(userId, &quot;User Name&quot;);<br>    }<br>    <br>    private EnrichedUser enrichUserData(User user) {<br>        simulateIoOperation(100);<br>        return new EnrichedUser(user.id(), user.name(), &quot;Additional data&quot;);<br>    }<br>    <br>    private EnrichedUser saveUser(EnrichedUser user) {<br>        simulateIoOperation(30);<br>        return user;<br>    }<br>}<br><br>// Supporting records<br>record User(String id, String name) {}<br>record EnrichedUser(String id, String name, String additionalData) {}</pre><p><strong>Key Insight:</strong> Virtual threads allow you to write simple, sequential code while achieving the same scalability as complex async code.</p><h3>When Blocking Operations Become Non-Blocking</h3><p>Virtual threads automatically handle blocking operations by parking and unparking from carrier threads:</p><pre>public class BlockingOperationsDemo {<br>    <br>    public void demonstrateBlockingBehavior() {<br>        System.out.println(&quot;Demonstrating virtual thread blocking behavior...&quot;);<br>        <br>        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {<br>            // Launch many virtual threads that perform blocking operations<br>            for (int i = 0; i &lt; 1000; i++) {<br>                final int taskId = i;<br>                executor.submit(() -&gt; performBlockingOperations(taskId));<br>            }<br>        }<br>        <br>        System.out.println(&quot;All blocking operations completed!&quot;);<br>    }<br>    <br>    private void performBlockingOperations(int taskId) {<br>        System.out.println(&quot;Task &quot; + taskId + &quot; started on: &quot; + <br>            Thread.currentThread().getName());<br>        <br>        try {<br>            // File I/O - blocking operation<br>            performFileOperation();<br>            <br>            // Network I/O - blocking operation  <br>            performNetworkOperation();<br>            <br>            // Thread.sleep - blocking operation<br>            Thread.sleep(100);<br>            <br>            // Synchronized block - potentially blocking<br>            performSynchronizedOperation();<br>            <br>        } catch (InterruptedException | IOException e) {<br>            Thread.currentThread().interrupt();<br>        }<br>        <br>        System.out.println(&quot;Task &quot; + taskId + &quot; completed on: &quot; + <br>            Thread.currentThread().getName());<br>    }<br>    <br>    private void performFileOperation() throws IOException {<br>        // Virtual thread will be parked during I/O<br>        Path tempFile = Files.createTempFile(&quot;vthread&quot;, &quot;.tmp&quot;);<br>        Files.writeString(tempFile, &quot;Virtual thread data&quot;);<br>        String content = Files.readString(tempFile);<br>        Files.deleteIfExists(tempFile);<br>    }<br>    <br>    private void performNetworkOperation() {<br>        // Virtual thread will be parked during network I/O<br>        try (var socket = new Socket(&quot;httpbin.org&quot;, 80)) {<br>            socket.getOutputStream().write(&quot;GET / HTTP/1.1\r\n\r\n&quot;.getBytes());<br>            try (var reader = new BufferedReader(<br>                    new InputStreamReader(socket.getInputStream()))) {<br>                reader.readLine(); // Read just the first line<br>            }<br>        } catch (IOException e) {<br>            // Handle network errors gracefully<br>        }<br>    }<br>    <br>    private synchronized void performSynchronizedOperation() {<br>        // Virtual thread may be pinned to carrier thread here<br>        try {<br>            Thread.sleep(10);<br>        } catch (InterruptedException e) {<br>            Thread.currentThread().interrupt();<br>        }<br>    }<br>}</pre><h4>Limitations and Pinning — What You Need to Know</h4><p>Virtual threads aren’t magic. There are important limitations to understand:</p><h4>1. Thread Pinning</h4><p>Virtual threads can be “pinned” to carrier threads in certain situations:</p><pre>public class ThreadPinningExamples {<br>    private final Object lock = new Object();<br>    <br>    public void demonstratePinningCauses() {<br>        System.out.println(&quot;Demonstrating thread pinning scenarios...&quot;);<br>        <br>        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {<br>            <br>            // Pinning Cause 1: synchronized blocks/methods<br>            executor.submit(this::synchronizedBlockPinning);<br>            <br>            // Pinning Cause 2: JNI calls<br>            executor.submit(this::jniCallPinning);<br>            <br>            // NON-pinning: ReentrantLock (recommended alternative)<br>            executor.submit(this::reentrantLockNonPinning);<br>        }<br>    }<br>    <br>    private void synchronizedBlockPinning() {<br>        synchronized (lock) {<br>            System.out.println(&quot;PINNED: Inside synchronized block on &quot; + <br>                Thread.currentThread().getName());<br>            try {<br>                Thread.sleep(1000); // Virtual thread is pinned during this sleep<br>            } catch (InterruptedException e) {<br>                Thread.currentThread().interrupt();<br>            }<br>        }<br>    }<br>    <br>    private void jniCallPinning() {<br>        // JNI calls also cause pinning<br>        System.out.println(&quot;PINNED: JNI call on &quot; + Thread.currentThread().getName());<br>        System.currentTimeMillis(); // This is actually a JNI call<br>        try {<br>            Thread.sleep(100);<br>        } catch (InterruptedException e) {<br>            Thread.currentThread().interrupt();<br>        }<br>    }<br>    <br>    private final ReentrantLock reentrantLock = new ReentrantLock();<br>    <br>    private void reentrantLockNonPinning() {<br>        reentrantLock.lock();<br>        try {<br>            System.out.println(&quot;NOT PINNED: Using ReentrantLock on &quot; + <br>                Thread.currentThread().getName());<br>            Thread.sleep(1000); // Virtual thread can be parked/unparked<br>        } catch (InterruptedException e) {<br>            Thread.currentThread().interrupt();<br>        } finally {<br>            reentrantLock.unlock();<br>        }<br>    }<br>}</pre><h4>2. CPU-Intensive Tasks</h4><p>Virtual threads are optimized for I/O-bound work, not CPU-intensive tasks:</p><pre>public class CpuIntensiveTasksDemo {<br>    <br>    public void compareTaskTypes() {<br>        System.out.println(&quot;Comparing I/O-bound vs CPU-bound tasks with virtual threads...&quot;);<br>        <br>        // I/O-bound tasks - Perfect for virtual threads<br>        testIoBoundTasks();<br>        <br>        // CPU-bound tasks - Better with platform threads<br>        testCpuBoundTasks();<br>    }<br>    <br>    private void testIoBoundTasks() {<br>        System.out.println(&quot;\n=== I/O-Bound Tasks (Virtual Threads Shine) ===&quot;);<br>        long startTime = System.currentTimeMillis();<br>        <br>        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {<br>            List&lt;Future&lt;String&gt;&gt; futures = new ArrayList&lt;&gt;();<br>            <br>            for (int i = 0; i &lt; 1000; i++) {<br>                futures.add(executor.submit(() -&gt; {<br>                    // Simulate I/O operation<br>                    try {<br>                        Thread.sleep(100); // 100ms I/O wait<br>                        return &quot;I/O task completed&quot;;<br>                    } catch (InterruptedException e) {<br>                        Thread.currentThread().interrupt();<br>                        return &quot;Interrupted&quot;;<br>                    }<br>                }));<br>            }<br>            <br>            // Wait for completion<br>            futures.forEach(future -&gt; {<br>                try {<br>                    future.get();<br>                } catch (ExecutionException | InterruptedException e) {<br>                    Thread.currentThread().interrupt();<br>                }<br>            });<br>        }<br>        <br>        long endTime = System.currentTimeMillis();<br>        System.out.println(&quot;1000 I/O-bound tasks completed in: &quot; + <br>            (endTime - startTime) + &quot;ms&quot;);<br>    }<br>    <br>    private void testCpuBoundTasks() {<br>        System.out.println(&quot;\n=== CPU-Bound Tasks (Consider Platform Threads) ===&quot;);<br>        long startTime = System.currentTimeMillis();<br>        <br>        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {<br>            List&lt;Future&lt;Long&gt;&gt; futures = new ArrayList&lt;&gt;();<br>            <br>            for (int i = 0; i &lt; 1000; i++) {<br>                final int taskId = i;<br>                futures.add(executor.submit(() -&gt; {<br>                    // CPU-intensive task<br>                    return performCpuIntensiveCalculation(taskId);<br>                }));<br>            }<br>            <br>            // Wait for completion<br>            futures.forEach(future -&gt; {<br>                try {<br>                    future.get();<br>                } catch (ExecutionException | InterruptedException e) {<br>                    Thread.currentThread().interrupt();<br>                }<br>            });<br>        }<br>        <br>        long endTime = System.currentTimeMillis();<br>        System.out.println(&quot;1000 CPU-bound tasks completed in: &quot; + <br>            (endTime - startTime) + &quot;ms&quot;);<br>        System.out.println(&quot;Note: For CPU-bound work, consider using &quot; +<br>            &quot;Runtime.getRuntime().availableProcessors() platform threads instead&quot;);<br>    }<br>    <br>    private long performCpuIntensiveCalculation(int taskId) {<br>        // Simulate CPU-intensive work - calculating prime numbers<br>        long result = 0;<br>        for (int i = taskId * 1000; i &lt; (taskId + 1) * 1000; i++) {<br>            if (isPrime(i)) {<br>                result += i;<br>            }<br>        }<br>        return result;<br>    }<br>    <br>    private boolean isPrime(int n) {<br>        if (n &lt; 2) return false;<br>        for (int i = 2; i &lt;= Math.sqrt(n); i++) {<br>            if (n % i == 0) return false;<br>        }<br>        return true;<br>    }<br>}</pre><h3>Best Practices for Virtual Threads</h3><h4>1. Use Virtual Threads for I/O-Heavy Workloads</h4><pre>// Perfect use case<br>public class ApiGatewayService {<br>    <br>    public void handleRequest(String requestId) {<br>        Thread.ofVirtual().start(() -&gt; {<br>            try {<br>                // Multiple I/O operations - perfect for virtual threads<br>                User user = fetchUserFromDatabase(requestId);<br>                List&lt;Permission&gt; permissions = fetchPermissionsFromCache(user.id());<br>                String response = callDownstreamService(user, permissions);<br>                sendResponse(requestId, response);<br>            } catch (Exception e) {<br>                sendError(requestId, e);<br>            }<br>        });<br>    }<br>}</pre><h4>2. Prefer ReentrantLock Over Synchronized</h4><pre>public class SynchronizationBestPractices {<br>    private final ReentrantLock lock = new ReentrantLock();<br>    private final Object synchronizedLock = new Object();<br>    <br>    // Avoid: synchronized causes pinning<br>    public synchronized void badSynchronizedMethod() {<br>        try {<br>            Thread.sleep(1000); // Virtual thread pinned for 1 second<br>        } catch (InterruptedException e) {<br>            Thread.currentThread().interrupt();<br>        }<br>    }<br>    <br>    // Prefer: ReentrantLock allows parking<br>    public void goodLockMethod() {<br>        lock.lock();<br>        try {<br>            Thread.sleep(1000); // Virtual thread can be parked/unparked<br>        } catch (InterruptedException e) {<br>            Thread.currentThread().interrupt();<br>        } finally {<br>            lock.unlock();<br>        }<br>    }<br>}</pre><h4>3. Don’t Pool Virtual Threads</h4><pre>public class VirtualThreadAntipatterns {<br>    <br>    // Don&#39;t do this - defeats the purpose of virtual threads<br>    public void antipatternPooledVirtualThreads() {<br>        try (var executor = Executors.newFixedThreadPool(100, <br>                Thread.ofVirtual().factory())) {<br>            // This limits you to 100 concurrent tasks - wasteful!<br>            for (int i = 0; i &lt; 10000; i++) {<br>                executor.submit(() -&gt; performIoTask());<br>            }<br>        }<br>    }<br>    <br>    // Do this - unlimited virtual threads<br>    public void correctUnlimitedVirtualThreads() {<br>        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {<br>            // Can handle all 10,000 tasks concurrently<br>            for (int i = 0; i &lt; 10000; i++) {<br>                executor.submit(() -&gt; performIoTask());<br>            }<br>        }<br>    }<br>    <br>    private void performIoTask() {<br>        try {<br>            Thread.sleep(1000); // Simulate I/O<br>        } catch (InterruptedException e) {<br>            Thread.currentThread().interrupt();<br>        }<br>    }<br>}</pre><h4>4. Monitor Virtual Thread Performance</h4><pre>public class VirtualThreadMonitoring {<br>    <br>    public void monitorVirtualThreadPerformance() {<br>        // Enable JFR events for virtual threads<br>        System.setProperty(&quot;jdk.tracePinnedThreads&quot;, &quot;full&quot;);<br>        <br>        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {<br>            long startTime = System.currentTimeMillis();<br>            List&lt;Future&lt;Void&gt;&gt; futures = new ArrayList&lt;&gt;();<br>            <br>            for (int i = 0; i &lt; 10000; i++) {<br>                futures.add(executor.submit(() -&gt; {<br>                    performMonitoredTask();<br>                    return null;<br>                }));<br>            }<br>            <br>            // Wait for all tasks<br>            futures.forEach(future -&gt; {<br>                try {<br>                    future.get();<br>                } catch (ExecutionException | InterruptedException e) {<br>                    Thread.currentThread().interrupt();<br>                }<br>            });<br>            <br>            long endTime = System.currentTimeMillis();<br>            System.out.println(&quot;10,000 virtual thread tasks completed in: &quot; + <br>                (endTime - startTime) + &quot;ms&quot;);<br>            <br>            // Print JVM statistics<br>            printVirtualThreadStats();<br>        }<br>    }<br>    <br>    private void performMonitoredTask() {<br>        try {<br>            // Mix of different operations<br>            Thread.sleep(100);  // I/O simulation<br>            doSomeComputation(); // CPU work<br>        } catch (InterruptedException e) {<br>            Thread.currentThread().interrupt();<br>        }<br>    }<br>    <br>    private void doSomeComputation() {<br>        // Light CPU work<br>        int sum = 0;<br>        for (int i = 0; i &lt; 1000; i++) {<br>            sum += i * i;<br>        }<br>    }<br>    <br>    private void printVirtualThreadStats() {<br>        // Access virtual thread metrics (Java 21+)<br>        var threadMXBean = ManagementFactory.getThreadMXBean();<br>        long totalThreads = threadMXBean.getThreadCount();<br>        long peakThreads = threadMXBean.getPeakThreadCount();<br>        <br>        System.out.println(&quot;Thread Statistics:&quot;);<br>        System.out.println(&quot;  Current threads: &quot; + totalThreads);<br>        System.out.println(&quot;  Peak threads: &quot; + peakThreads);<br>        <br>        // Memory usage<br>        var memoryMXBean = ManagementFactory.getMemoryMXBean();<br>        var heapUsage = memoryMXBean.getHeapMemoryUsage();<br>        System.out.println(&quot;  Heap usage: &quot; + <br>            (heapUsage.getUsed() / 1024 / 1024) + &quot;MB&quot;);<br>    }<br>}</pre><h3>Migration Strategies: From Platform Threads to Virtual Threads</h3><p>Migrating existing code to virtual threads is often straightforward, but requires thoughtful planning:</p><h4>1. Executor Service Migration</h4><pre>public class MigrationStrategies {<br>    <br>    // Before: Platform thread executor<br>    public class OldService {<br>        private final ExecutorService executor = <br>            Executors.newFixedThreadPool(200);<br>        <br>        public void processRequests(List&lt;String&gt; requests) {<br>            for (String request : requests) {<br>                executor.submit(() -&gt; {<br>                    processRequest(request);<br>                });<br>            }<br>        }<br>        <br>        public void shutdown() {<br>            executor.shutdown();<br>        }<br>    }<br>    <br>    // After: Virtual thread executor<br>    public class NewService {<br>        // No need to configure pool size!<br>        private final ExecutorService executor = <br>            Executors.newVirtualThreadPerTaskExecutor();<br>        <br>        public void processRequests(List&lt;String&gt; requests) {<br>            for (String request : requests) {<br>                executor.submit(() -&gt; {<br>                    processRequest(request); // Same business logic<br>                });<br>            }<br>        }<br>        <br>        public void shutdown() {<br>            executor.shutdown();<br>        }<br>    }<br>    <br>    private void processRequest(String request) {<br>        // Simulate I/O-heavy processing<br>        try {<br>            Thread.sleep(100); // Database call<br>            Thread.sleep(200); // External API call<br>            Thread.sleep(50);  // Cache update<br>        } catch (InterruptedException e) {<br>            Thread.currentThread().interrupt();<br>        }<br>    }<br>}</pre><h4>2. CompletableFuture to Virtual Threads</h4><pre>public class AsyncToVirtualThreadMigration {<br>    <br>    // Complex async chain - hard to read and debug<br>    public CompletableFuture&lt;OrderResult&gt; processOrderAsync(Order order) {<br>        return validateOrderAsync(order)<br>            .thenCompose(validOrder -&gt; reserveInventoryAsync(validOrder))<br>            .thenCompose(reservation -&gt; processPaymentAsync(order, reservation))<br>            .thenCompose(payment -&gt; createShipmentAsync(order, payment))<br>            .thenApply(shipment -&gt; new OrderResult(order.id(), shipment.trackingNumber()))<br>            .exceptionally(throwable -&gt; {<br>                log.error(&quot;Order processing failed&quot;, throwable);<br>                return new OrderResult(order.id(), &quot;FAILED: &quot; + throwable.getMessage());<br>            });<br>    }<br>    <br>    // Simple synchronous code with virtual threads - easy to read and debug<br>    public OrderResult processOrder(Order order) {<br>        Thread.ofVirtual().start(() -&gt; {<br>            try {<br>                var validOrder = validateOrder(order);<br>                var reservation = reserveInventory(validOrder);<br>                var payment = processPayment(order, reservation);<br>                var shipment = createShipment(order, payment);<br>                <br>                return new OrderResult(order.id(), shipment.trackingNumber());<br>                <br>            } catch (Exception e) {<br>                log.error(&quot;Order processing failed&quot;, e);<br>                return new OrderResult(order.id(), &quot;FAILED: &quot; + e.getMessage());<br>            }<br>        });<br>    }<br>    <br>    // Supporting synchronous methods (much simpler than async versions)<br>    private Order validateOrder(Order order) {<br>        simulateIoOperation(50); // Database validation<br>        if (order.items().isEmpty()) {<br>            throw new IllegalArgumentException(&quot;Order has no items&quot;);<br>        }<br>        return order;<br>    }<br>    <br>    private InventoryReservation reserveInventory(Order order) {<br>        simulateIoOperation(100); // Inventory service call<br>        return new InventoryReservation(order.id(), &quot;RESERVED&quot;);<br>    }<br>    <br>    private Payment processPayment(Order order, InventoryReservation reservation) {<br>        simulateIoOperation(200); // Payment gateway call<br>        return new Payment(order.id(), order.total());<br>    }<br>    <br>    private Shipment createShipment(Order order, Payment payment) {<br>        simulateIoOperation(75); // Shipping service call<br>        return new Shipment(order.id(), &quot;TRACK-&quot; + System.currentTimeMillis());<br>    }<br>}<br><br>// Supporting records<br>record Order(String id, List&lt;String&gt; items, double total) {}<br>record InventoryReservation(String orderId, String status) {}<br>record Payment(String orderId, double amount) {}<br>record Shipment(String orderId, String trackingNumber) {}<br>record OrderResult(String orderId, String result) {}</pre><h4>3. Structured Concurrency (Preview Feature)</h4><p>Java 21 also introduces Structured Concurrency as a preview feature, which pairs beautifully with virtual threads:</p><pre>public class StructuredConcurrencyExample {<br>    <br>    // Traditional approach - complex error handling and cancellation<br>    public UserProfile fetchUserProfileTraditional(String userId) <br>            throws ExecutionException, InterruptedException {<br>        <br>        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {<br>            var userFuture = executor.submit(() -&gt; fetchUser(userId));<br>            var preferencesFuture = executor.submit(() -&gt; fetchPreferences(userId));<br>            var historyFuture = executor.submit(() -&gt; fetchHistory(userId));<br>            <br>            // Wait for all to complete<br>            var user = userFuture.get();<br>            var preferences = preferencesFuture.get();<br>            var history = historyFuture.get();<br>            <br>            return new UserProfile(user, preferences, history);<br>        }<br>    }<br>    <br>    // Structured Concurrency approach - clean and safe<br>    public UserProfile fetchUserProfileStructured(String userId) <br>            throws ExecutionException, InterruptedException {<br>        <br>        try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {<br>            // Start all subtasks<br>            var userTask = scope.fork(() -&gt; fetchUser(userId));<br>            var preferencesTask = scope.fork(() -&gt; fetchPreferences(userId));<br>            var historyTask = scope.fork(() -&gt; fetchHistory(userId));<br>            <br>            // Wait for all to complete or any to fail<br>            scope.join()           // Wait for all subtasks<br>                 .throwIfFailed(); // Propagate any exceptions<br>            <br>            // All succeeded - collect results<br>            return new UserProfile(<br>                userTask.resultNow(),<br>                preferencesTask.resultNow(), <br>                historyTask.resultNow()<br>            );<br>        }<br>    }<br>    <br>    // Race condition example - first successful response wins<br>    public String fetchFromMultipleSources(String query) <br>            throws ExecutionException, InterruptedException {<br>        <br>        try (var scope = new StructuredTaskScope.ShutdownOnSuccess&lt;String&gt;()) {<br>            // Start multiple competing tasks<br>            scope.fork(() -&gt; searchPrimaryDatabase(query));<br>            scope.fork(() -&gt; searchSecondaryDatabase(query));<br>            scope.fork(() -&gt; searchExternalAPI(query));<br>            <br>            // Return first successful result<br>            return scope.join().result();<br>        }<br>    }<br>    <br>    private User fetchUser(String userId) {<br>        simulateIoOperation(100);<br>        return new User(userId, &quot;User Name&quot;);<br>    }<br>    <br>    private Preferences fetchPreferences(String userId) {<br>        simulateIoOperation(150);<br>        return new Preferences(userId, Map.of(&quot;theme&quot;, &quot;dark&quot;));<br>    }<br>    <br>    private History fetchHistory(String userId) {<br>        simulateIoOperation(200);<br>        return new History(userId, List.of(&quot;login&quot;, &quot;view_profile&quot;));<br>    }<br>    <br>    private String searchPrimaryDatabase(String query) {<br>        simulateIoOperation(100 + (int)(Math.random() * 200));<br>        return &quot;Primary DB result for: &quot; + query;<br>    }<br>    <br>    private String searchSecondaryDatabase(String query) {<br>        simulateIoOperation(150 + (int)(Math.random() * 100));<br>        return &quot;Secondary DB result for: &quot; + query;<br>    }<br>    <br>    private String searchExternalAPI(String query) {<br>        simulateIoOperation(300 + (int)(Math.random() * 500));<br>        return &quot;External API result for: &quot; + query;<br>    }<br>}<br><br>// Supporting records<br>record User(String id, String name) {}<br>record Preferences(String userId, Map&lt;String, String&gt; settings) {}<br>record History(String userId, List&lt;String&gt; actions) {}<br>record UserProfile(User user, Preferences preferences, History history) {}</pre><h3>Performance Benchmarking: The Numbers Don’t Lie</h3><p>Let’s create a comprehensive benchmark to demonstrate virtual threads’ performance characteristics:</p><pre>public class VirtualThreadBenchmark {<br>    <br>    public static void main(String[] args) {<br>        var benchmark = new VirtualThreadBenchmark();<br>        <br>        System.out.println(&quot;=== Virtual Thread Performance Benchmark ===\n&quot;);<br>        <br>        // Test different scenarios<br>        benchmark.benchmarkHighConcurrencyIoTasks();<br>        benchmark.benchmarkMemoryUsage();<br>        benchmark.benchmarkThroughput();<br>    }<br>    <br>    public void benchmarkHighConcurrencyIoTasks() {<br>        System.out.println(&quot;1. High Concurrency I/O Tasks Benchmark&quot;);<br>        System.out.println(&quot;   Testing 50,000 concurrent tasks with 1-second I/O delay each&quot;);<br>        <br>        // Platform threads (limited by thread pool)<br>        benchmarkTaskExecution(&quot;Platform Threads (Pool=1000)&quot;, <br>            50000, () -&gt; Executors.newFixedThreadPool(1000));<br>        <br>        // Virtual threads (unlimited)<br>        benchmarkTaskExecution(&quot;Virtual Threads&quot;, <br>            50000, Executors::newVirtualThreadPerTaskExecutor);<br>        <br>        System.out.println();<br>    }<br>    <br>    public void benchmarkMemoryUsage() {<br>        System.out.println(&quot;2. Memory Usage Benchmark&quot;);<br>        System.out.println(&quot;   Creating 100,000 idle threads&quot;);<br>        <br>        Runtime runtime = Runtime.getRuntime();<br>        <br>        // Measure baseline memory<br>        System.gc();<br>        long baselineMemory = runtime.totalMemory() - runtime.freeMemory();<br>        <br>        List&lt;Thread&gt; threads = new ArrayList&lt;&gt;();<br>        <br>        // Create 100,000 virtual threads<br>        long startTime = System.currentTimeMillis();<br>        for (int i = 0; i &lt; 100000; i++) {<br>            Thread vt = Thread.ofVirtual().start(() -&gt; {<br>                try {<br>                    Thread.sleep(10000); // Sleep for 10 seconds<br>                } catch (InterruptedException e) {<br>                    Thread.currentThread().interrupt();<br>                }<br>            });<br>            threads.add(vt);<br>        }<br>        long creationTime = System.currentTimeMillis() - startTime;<br>        <br>        // Measure memory after creation<br>        System.gc();<br>        long afterCreationMemory = runtime.totalMemory() - runtime.freeMemory();<br>        long memoryUsed = afterCreationMemory - baselineMemory;<br>        <br>        System.out.printf(&quot;   Created 100,000 virtual threads in %d ms%n&quot;, creationTime);<br>        System.out.printf(&quot;   Memory used: %.2f MB%n&quot;, memoryUsed / 1024.0 / 1024.0);<br>        System.out.printf(&quot;   Memory per thread: %.2f KB%n&quot;, <br>            memoryUsed / 100000.0 / 1024.0);<br>        <br>        // Interrupt all threads to clean up<br>        threads.forEach(Thread::interrupt);<br>        <br>        System.out.println();<br>    }<br>    <br>    public void benchmarkThroughput() {<br>        System.out.println(&quot;3. Throughput Benchmark&quot;);<br>        System.out.println(&quot;   Processing requests with varying I/O delays&quot;);<br>        <br>        int[] ioDelays = {10, 50, 100, 500, 1000}; // milliseconds<br>        int requestCount = 10000;<br>        <br>        for (int delay : ioDelays) {<br>            System.out.printf(&quot;   I/O Delay: %d ms%n&quot;, delay);<br>            <br>            // Platform threads<br>            long platformTime = measureThroughput(&quot;Platform&quot;, requestCount, <br>                delay, () -&gt; Executors.newFixedThreadPool(200));<br>            <br>            // Virtual threads  <br>            long virtualTime = measureThroughput(&quot;Virtual&quot;, requestCount, <br>                delay, Executors::newVirtualThreadPerTaskExecutor);<br>            <br>            double improvement = (double) platformTime / virtualTime;<br>            System.out.printf(&quot;     Virtual threads are %.2fx faster%n&quot;, improvement);<br>            System.out.println();<br>        }<br>    }<br>    <br>    private void benchmarkTaskExecution(String description, int taskCount, <br>            Supplier&lt;ExecutorService&gt; executorSupplier) {<br>        <br>        long startTime = System.currentTimeMillis();<br>        <br>        try (var executor = executorSupplier.get()) {<br>            List&lt;Future&lt;Void&gt;&gt; futures = new ArrayList&lt;&gt;();<br>            <br>            for (int i = 0; i &lt; taskCount; i++) {<br>                futures.add(executor.submit(() -&gt; {<br>                    try {<br>                        Thread.sleep(1000); // 1 second I/O simulation<br>                        return null;<br>                    } catch (InterruptedException e) {<br>                        Thread.currentThread().interrupt();<br>                        return null;<br>                    }<br>                }));<br>            }<br>            <br>            // Wait for all to complete<br>            for (Future&lt;Void&gt; future : futures) {<br>                try {<br>                    future.get();<br>                } catch (ExecutionException | InterruptedException e) {<br>                    Thread.currentThread().interrupt();<br>                }<br>            }<br>        }<br>        <br>        long endTime = System.currentTimeMillis();<br>        long duration = endTime - startTime;<br>        double throughput = (taskCount * 1000.0) / duration;<br>        <br>        System.out.printf(&quot;   %s: %d ms (%.2f tasks/sec)%n&quot;, <br>            description, duration, throughput);<br>    }<br>    <br>    private long measureThroughput(String type, int requestCount, int ioDelay,<br>            Supplier&lt;ExecutorService&gt; executorSupplier) {<br>        <br>        long startTime = System.currentTimeMillis();<br>        <br>        try (var executor = executorSupplier.get()) {<br>            List&lt;Future&lt;Void&gt;&gt; futures = new ArrayList&lt;&gt;();<br>            <br>            for (int i = 0; i &lt; requestCount; i++) {<br>                futures.add(executor.submit(() -&gt; {<br>                    try {<br>                        Thread.sleep(ioDelay);<br>                        return null;<br>                    } catch (InterruptedException e) {<br>                        Thread.currentThread().interrupt();<br>                        return null;<br>                    }<br>                }));<br>            }<br>            <br>            // Wait for all to complete<br>            futures.forEach(future -&gt; {<br>                try {<br>                    future.get();<br>                } catch (ExecutionException | InterruptedException e) {<br>                    Thread.currentThread().interrupt();<br>                }<br>            });<br>        }<br>        <br>        long endTime = System.currentTimeMillis();<br>        long duration = endTime - startTime;<br>        <br>        System.out.printf(&quot;     %s threads: %d ms%n&quot;, type, duration);<br>        return duration;<br>    }<br>    <br>    private void simulateIoOperation(long millis) {<br>        try {<br>            Thread.sleep(millis);<br>        } catch (InterruptedException e) {<br>            Thread.currentThread().interrupt();<br>        }<br>    }<br>}</pre><h3>Common Anti-Patterns to Avoid</h3><h4>1. Using Virtual Threads for CPU-Intensive Work</h4><pre>// Anti-pattern: CPU-intensive work with virtual threads<br>public class CpuIntensiveAntipattern {<br>    public void badCpuIntensiveWork() {<br>        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {<br>            for (int i = 0; i &lt; 1000; i++) {<br>                executor.submit(() -&gt; {<br>                    // This will pin the virtual thread and waste carrier threads<br>                    calculatePrimes(1_000_000);<br>                });<br>            }<br>        }<br>    }<br>    <br>    // Better: Use platform threads for CPU work<br>    public void goodCpuIntensiveWork() {<br>        int processorCount = Runtime.getRuntime().availableProcessors();<br>        try (var executor = Executors.newFixedThreadPool(processorCount)) {<br>            for (int i = 0; i &lt; 1000; i++) {<br>                executor.submit(() -&gt; {<br>                    calculatePrimes(1_000_000);<br>                });<br>            }<br>        }<br>    }<br>    <br>    private void calculatePrimes(int limit) {<br>        // CPU-intensive prime calculation<br>        for (int i = 2; i &lt; limit; i++) {<br>            isPrime(i);<br>        }<br>    }<br>}</pre><h4>2. Excessive ThreadLocal Usage</h4><pre>// Anti-pattern: Heavy ThreadLocal usage<br>public class ThreadLocalAntipattern {<br>    private static final ThreadLocal&lt;ExpensiveObject&gt; EXPENSIVE_THREAD_LOCAL = <br>        ThreadLocal.withInitial(ExpensiveObject::new);<br>    <br>    public void processWithThreadLocal() {<br>        // With millions of virtual threads, this creates millions of objects<br>        ExpensiveObject obj = EXPENSIVE_THREAD_LOCAL.get();<br>        obj.process();<br>    }<br>    <br>    // Better: Pass context explicitly or use ScopedValue (preview)<br>    public void processWithExplicitContext(ExpensiveObject context) {<br>        context.process();<br>    }<br>}<br><br>class ExpensiveObject {<br>    private final byte[] largeBuffer = new byte[1024 * 1024]; // 1MB per thread!<br>    <br>    public void process() {<br>        // Some processing logic<br>    }<br>}</pre><h4>3. Blocking on Virtual Thread Results</h4><pre>// Anti-pattern: Blocking the caller thread<br>public class BlockingAntipattern {<br>    public String processRequestBlocking(String request) {<br>        try {<br>            return Thread.ofVirtual().start(() -&gt; {<br>                return performSlowOperation(request);<br>            }).join(); // Blocking the caller!<br>        } catch (InterruptedException e) {<br>            Thread.currentThread().interrupt();<br>            return &quot;Error&quot;;<br>        }<br>    }<br>    <br>    // Better: Return a Future or use callback<br>    public Future&lt;String&gt; processRequestNonBlocking(String request) {<br>        return CompletableFuture.supplyAsync(() -&gt; {<br>            return performSlowOperation(request);<br>        }, Executors.newVirtualThreadPerTaskExecutor());<br>    }<br>}</pre><h3>The Future of Concurrency in Java</h3><p>Virtual threads represent a fundamental shift in how we think about concurrency in Java. They enable us to write simple, sequential code that scales to millions of concurrent operations. This is particularly important as we move toward more distributed, microservice-based architectures where each service handles thousands of concurrent requests.</p><h3>Integration with Project Loom’s Broader Vision</h3><p>Virtual threads are part of Project Loom’s broader mission to make concurrency in Java more accessible:</p><ul><li><strong>Structured Concurrency</strong> provides better patterns for managing concurrent subtasks</li><li><strong>Scoped Values</strong> offer a better alternative to ThreadLocal for virtual threads</li><li><strong>Foreign Function &amp; Memory API</strong> enables efficient interaction with native code</li></ul><h3>Conclusion</h3><p>Virtual threads in Java 21 solve one of the most persistent problems in server-side Java development: the trade-off between code simplicity and scalability. They allow us to write straightforward, sequential code that can handle millions of concurrent operations without the complexity of asynchronous programming or the resource overhead of platform threads.</p><p>Key takeaways for adopting virtual threads:</p><ol><li><strong>Perfect for I/O-bound workloads</strong> — Database calls, HTTP requests, file operations</li><li><strong>Write simple, sequential code</strong> — No more complex async chains or callback hell</li><li><strong>Avoid thread pooling</strong> — Create virtual threads on-demand without limits</li><li><strong>Prefer ReentrantLock over synchronized</strong> — To avoid thread pinning</li><li><strong>Monitor for pinning scenarios</strong> — Use JFR and diagnostic flags</li><li><strong>Consider structured concurrency</strong> — For managing complex concurrent operations</li></ol><p>As we embrace virtual threads, we’re not just adopting a new feature — we’re returning to the simplicity that makes Java productive while achieving the scale that modern applications demand. The future of concurrent Java programming has never looked brighter.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40e74ed94468" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sequenced Collections and Maps]]></title>
            <link>https://medium.com/@tadeoaragoon/sequenced-collections-and-maps-f8265c88528b?source=rss-e126e053b725------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8265c88528b</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[sequenced-collection]]></category>
            <category><![CDATA[collection]]></category>
            <category><![CDATA[java-21-features]]></category>
            <dc:creator><![CDATA[Tadeo Aragón]]></dc:creator>
            <pubDate>Sat, 23 Aug 2025 00:50:58 GMT</pubDate>
            <atom:updated>2025-08-23T00:56:37.280Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xe0xxap_k5h0EGQjvZw8Gg.png" /></figure><h4>The Problem We’ve All Faced</h4><p>Let’s start with a scenario every Java developer has encountered. Imagine you need to get the first and last elements from different collection types:</p><pre>// Before Java 21 - The inconsistent nightmare<br>List&lt;String&gt; list = Arrays.asList(&quot;first&quot;, &quot;middle&quot;, &quot;last&quot;);<br>String firstFromList = list.get(0);                    // Easy enough<br>String lastFromList = list.get(list.size() - 1);      // Verbose and error-prone<br><br>LinkedHashSet&lt;String&gt; set = new LinkedHashSet&lt;&gt;();<br>set.addAll(Arrays.asList(&quot;first&quot;, &quot;middle&quot;, &quot;last&quot;));<br>String firstFromSet = set.iterator().next();           // Different API<br>String lastFromSet = ???                               // No direct way!<br><br>TreeMap&lt;Integer, String&gt; map = new TreeMap&lt;&gt;();<br>map.put(1, &quot;first&quot;);<br>map.put(2, &quot;middle&quot;); <br>map.put(3, &quot;last&quot;);<br>String firstFromMap = map.firstEntry().getValue();     // Yet another API<br>String lastFromMap = map.lastEntry().getValue();       // At least this exists</pre><p>This inconsistency wasn’t just annoying — it was a source of bugs and made code harder to maintain. Each collection type had its own way (or no way at all) to access elements at the extremes.</p><h3>Enter Sequenced Collections: The Unified Solution</h3><p>Java 21 introduces three new interfaces that bring order to this chaos:</p><ul><li><strong>SequencedCollection&lt;E&gt;</strong> - For collections with well-defined encounter order</li><li><strong>SequencedSet&lt;E&gt;</strong> - For sets with well-defined encounter order</li><li><strong>SequencedMap&lt;K, V&gt;</strong> - For maps with well-defined encounter order</li></ul><h3>Understanding “Well-Defined Encounter Order”</h3><p>A collection has a <strong>well-defined encounter order</strong> if:</p><ul><li>Elements have a consistent, predictable order when iterated</li><li>This order remains stable across iterations (unless modified)</li><li>The order is meaningful to the collection’s contract</li></ul><p>Examples of collections with well-defined encounter order:</p><ul><li>ArrayList (insertion order)</li><li>LinkedHashSet (insertion order)</li><li>TreeSet (sorted order)</li><li>LinkedHashMap (insertion or access order)</li></ul><h3>The SequencedCollection Interface: Your New Best Friend</h3><p>Let’s explore the SequencedCollection&lt;E&gt; interface, which extends Collection&lt;E&gt;:</p><pre>public interface SequencedCollection&lt;E&gt; extends Collection&lt;E&gt; {<br>    // Add elements to the beginning and end<br>    void addFirst(E e);<br>    void addLast(E e);<br>    <br>    // Get elements from the beginning and end<br>    E getFirst();<br>    E getLast();<br>    <br>    // Remove elements from the beginning and end<br>    E removeFirst();<br>    E removeLast();<br>    <br>    // Get a reverse-ordered view<br>    SequencedCollection&lt;E&gt; reversed();<br>}</pre><h3>Practical Examples: The Power of Consistency</h3><p>Now, let’s see how Java 21 transforms our earlier nightmare into elegant, consistent code:</p><pre>// Java 21 - Consistent and clean<br>public class SequencedCollectionDemo {<br>    public static void demonstrateConsistency() {<br>        // All these collections now support the same operations!<br>        SequencedCollection&lt;String&gt; list = new ArrayList&lt;&gt;(<br>            Arrays.asList(&quot;first&quot;, &quot;middle&quot;, &quot;last&quot;));<br>        SequencedCollection&lt;String&gt; set = new LinkedHashSet&lt;&gt;(<br>            Arrays.asList(&quot;first&quot;, &quot;middle&quot;, &quot;last&quot;));<br>        <br>        // Consistent API across all collection types<br>        printFirstAndLast(&quot;ArrayList&quot;, list);<br>        printFirstAndLast(&quot;LinkedHashSet&quot;, set);<br>    }<br>    <br>    private static void printFirstAndLast(String type, <br>                                         SequencedCollection&lt;String&gt; collection) {<br>        System.out.println(type + &quot;:&quot;);<br>        System.out.println(&quot;  First: &quot; + collection.getFirst());<br>        System.out.println(&quot;  Last: &quot; + collection.getLast());<br>        System.out.println();<br>    }<br>}<br><br><br>/**<br>output:<br><br>ArrayList:<br>  First: first<br>  Last: last<br><br>LinkedHashSet:<br>  First: first<br>  Last: last<br><br>**/</pre><h3>Advanced Operations: Working with Both Ends</h3><p>The real power emerges when you need to manipulate collections from both ends:</p><pre>public class DequeOperationsExample {<br>    public static void demonstrateDequeOperations() {<br>        SequencedCollection&lt;String&gt; tasks = new ArrayDeque&lt;&gt;();<br>        <br>        // Building a priority task queue<br>        tasks.addFirst(&quot;URGENT: Fix production bug&quot;);<br>        tasks.addLast(&quot;Regular: Update documentation&quot;);<br>        tasks.addFirst(&quot;CRITICAL: Security patch&quot;);<br>        tasks.addLast(&quot;Low: Refactor utility class&quot;);<br>        <br>        System.out.println(&quot;Task queue (highest to lowest priority):&quot;);<br>        tasks.forEach(task -&gt; System.out.println(&quot;  &quot; + task));<br>        <br>        // Process most urgent task<br>        String urgentTask = tasks.removeFirst();<br>        System.out.println(&quot;\nProcessing: &quot; + urgentTask);<br>        <br>        // Defer least important task<br>        String deferredTask = tasks.removeLast();<br>        System.out.println(&quot;Deferred: &quot; + deferredTask);<br>    }<br>}</pre><h3>SequencedSet: Ordered Uniqueness</h3><p>The SequencedSet&lt;E&gt; interface extends both Set&lt;E&gt; and SequencedCollection&lt;E&gt;:</p><pre>public class SequencedSetExample {<br>    public static void demonstrateSequencedSet() {<br>        SequencedSet&lt;String&gt; userActions = new LinkedHashSet&lt;&gt;();<br>        <br>        // Track user actions in order, but avoid duplicates<br>        userActions.addLast(&quot;login&quot;);<br>        userActions.addLast(&quot;view_profile&quot;);<br>        userActions.addLast(&quot;edit_profile&quot;);<br>        userActions.addLast(&quot;view_profile&quot;); // Duplicate - won&#39;t be added<br>        userActions.addLast(&quot;logout&quot;);<br>        <br>        System.out.println(&quot;User action sequence:&quot;);<br>        userActions.forEach(System.out::println);<br>        <br>        System.out.println(&quot;\nFirst action: &quot; + userActions.getFirst());<br>        System.out.println(&quot;Last action: &quot; + userActions.getLast());<br>        <br>        // Get actions in reverse order<br>        System.out.println(&quot;\nReverse order:&quot;);<br>        userActions.reversed().forEach(System.out::println);<br>    }<br>}</pre><h3>SequencedMap: Ordered Key-Value Pairs</h3><p>The SequencedMap&lt;K, V&gt; interface brings similar benefits to maps:</p><pre>public interface SequencedMap&lt;K, V&gt; extends Map&lt;K, V&gt; {<br>    // Entry operations at both ends<br>    Map.Entry&lt;K, V&gt; firstEntry();<br>    Map.Entry&lt;K, V&gt; lastEntry();<br>    <br>    // Key operations at both ends  <br>    K firstKey();<br>    K lastKey();<br>    <br>    // Remove operations at both ends<br>    Map.Entry&lt;K, V&gt; pollFirstEntry();<br>    Map.Entry&lt;K, V&gt; pollLastEntry();<br>    <br>    // Value operations (new in Java 21)<br>    V putFirst(K key, V value);<br>    V putLast(K key, V value);<br>    <br>    // Reverse-ordered views<br>    SequencedMap&lt;K, V&gt; reversed();<br>    SequencedSet&lt;K&gt; sequencedKeySet();<br>    SequencedCollection&lt;V&gt; sequencedValues();<br>    SequencedSet&lt;Map.Entry&lt;K, V&gt;&gt; sequencedEntrySet();<br>}</pre><h3>Real-World SequencedMap Example</h3><p>Here’s a practical example using SequencedMap for a cache implementation:</p><pre>public class LRUCacheExample {<br>    public static void demonstrateLRUCache() {<br>        // LinkedHashMap maintains insertion order by default<br>        SequencedMap&lt;String, String&gt; cache = new LinkedHashMap&lt;&gt;();<br>        <br>        // Simulate cache operations<br>        cache.putLast(&quot;user:123&quot;, &quot;John Doe&quot;);<br>        cache.putLast(&quot;user:456&quot;, &quot;Jane Smith&quot;);<br>        cache.putLast(&quot;user:789&quot;, &quot;Bob Wilson&quot;);<br>        <br>        System.out.println(&quot;Cache contents (insertion order):&quot;);<br>        cache.sequencedEntrySet().forEach(entry -&gt; <br>            System.out.println(&quot;  &quot; + entry.getKey() + &quot; -&gt; &quot; + entry.getValue()));<br>        <br>        // Access user:123 (move to end in LRU implementation)<br>        String user = cache.get(&quot;user:123&quot;);<br>        System.out.println(&quot;\nAccessed: &quot; + user);<br>        <br>        // Remove least recently used item<br>        Map.Entry&lt;String, String&gt; lru = cache.pollFirstEntry();<br>        System.out.println(&quot;Removed LRU: &quot; + lru.getKey() + &quot; -&gt; &quot; + lru.getValue());<br>        <br>        // Show final state<br>        System.out.println(&quot;\nCache after LRU removal:&quot;);<br>        cache.sequencedEntrySet().forEach(entry -&gt; <br>            System.out.println(&quot;  &quot; + entry.getKey() + &quot; -&gt; &quot; + entry.getValue()));<br>    }<br>}</pre><h3>Creating Unmodifiable Sequenced Collections</h3><p>Java 21 enhances the Collections utility class with factory methods for unmodifiable sequenced collections:</p><pre>public class UnmodifiableSequencedDemo {<br>    public static void demonstrateUnmodifiableSequenced() {<br>        // Create unmodifiable sequenced collections<br>        SequencedCollection&lt;String&gt; unmodifiableList = <br>            Collections.unmodifiableSequencedCollection(<br>                new ArrayList&lt;&gt;(Arrays.asList(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;)));<br>        <br>        SequencedSet&lt;String&gt; unmodifiableSet = <br>            Collections.unmodifiableSequencedSet(<br>                new LinkedHashSet&lt;&gt;(Arrays.asList(&quot;x&quot;, &quot;y&quot;, &quot;z&quot;)));<br>        <br>        SequencedMap&lt;Integer, String&gt; unmodifiableMap = <br>            Collections.unmodifiableSequencedMap(<br>                new LinkedHashMap&lt;&gt;(Map.of(1, &quot;one&quot;, 2, &quot;two&quot;, 3, &quot;three&quot;)));<br>        <br>        // These work fine - reading operations<br>        System.out.println(&quot;First in list: &quot; + unmodifiableList.getFirst());<br>        System.out.println(&quot;Last in set: &quot; + unmodifiableSet.getLast());<br>        System.out.println(&quot;First entry in map: &quot; + unmodifiableMap.firstEntry());<br>        <br>        // These will throw UnsupportedOperationException<br>        try {<br>            unmodifiableList.addFirst(&quot;new&quot;);<br>        } catch (UnsupportedOperationException e) {<br>            System.out.println(&quot;Cannot modify unmodifiable collection: &quot; + e.getMessage());<br>        }<br>    }<br>}</pre><h3>Concurrent Collections: Thread-Safe Sequenced Operations</h3><p>The java.util.concurrent package has been retrofitted to support sequenced operations where appropriate:</p><pre>public class ConcurrentSequencedExample {<br>    public static void demonstrateConcurrentSequenced() {<br>        // ConcurrentLinkedDeque implements SequencedCollection<br>        SequencedCollection&lt;String&gt; concurrentQueue = new ConcurrentLinkedDeque&lt;&gt;();<br>        <br>        // Thread-safe operations at both ends<br>        ExecutorService executor = Executors.newFixedThreadPool(3);<br>        <br>        // Producer threads adding to both ends<br>        executor.submit(() -&gt; {<br>            for (int i = 0; i &lt; 5; i++) {<br>                concurrentQueue.addFirst(&quot;HIGH-&quot; + i);<br>                sleepQuietly(100);<br>            }<br>        });<br>        <br>        executor.submit(() -&gt; {<br>            for (int i = 0; i &lt; 5; i++) {<br>                concurrentQueue.addLast(&quot;LOW-&quot; + i);<br>                sleepQuietly(150);<br>            }<br>        });<br>        <br>        // Consumer thread processing from the front<br>        executor.submit(() -&gt; {<br>            for (int i = 0; i &lt; 10; i++) {<br>                try {<br>                    String item = concurrentQueue.removeFirst();<br>                    System.out.println(&quot;Processed: &quot; + item);<br>                } catch (NoSuchElementException e) {<br>                    System.out.println(&quot;Queue empty, waiting...&quot;);<br>                    sleepQuietly(200);<br>                    i--; // Retry<br>                }<br>            }<br>        });<br>        <br>        executor.shutdown();<br>    }<br>    <br>    private static void sleepQuietly(long millis) {<br>        try {<br>            Thread.sleep(millis);<br>        } catch (InterruptedException e) {<br>            Thread.currentThread().interrupt();<br>        }<br>    }<br>}</pre><h3>Best Practices and Migration Tips</h3><h4>1. Prefer Sequenced Interfaces in Method Signatures</h4><pre>// Good: Flexible and future-proof<br>public void processItems(SequencedCollection&lt;String&gt; items) {<br>    if (!items.isEmpty()) {<br>        String first = items.getFirst();<br>        String last = items.getLast();<br>        // Process first and last items<br>    }<br>}<br><br>// Less flexible: Tied to specific implementation<br>public void processItems(ArrayList&lt;String&gt; items) {<br>    if (!items.isEmpty()) {<br>        String first = items.get(0);<br>        String last = items.get(items.size() - 1);<br>        // Same logic, but less flexible<br>    }<br>}</pre><p>2. Use Reversed Views Instead of Creating New Collections</p><pre>// Efficient: No copying, just a different view<br>SequencedCollection&lt;String&gt; original = new ArrayList&lt;&gt;(Arrays.asList(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;));<br>SequencedCollection&lt;String&gt; reversed = original.reversed();<br><br>// Inefficient: Creates a new collection and copies elements<br>List&lt;String&gt; inefficientReverse = new ArrayList&lt;&gt;(original);<br>Collections.reverse(inefficientReverse);</pre><h3>3. Handle Empty Collections Gracefully</h3><pre>public void safeSequencedOperations(SequencedCollection&lt;String&gt; collection) {<br>    // Always check for emptiness before accessing first/last<br>    if (!collection.isEmpty()) {<br>        String first = collection.getFirst();<br>        String last = collection.getLast();<br>        // Safe operations<br>    } else {<br>        // Handle empty collection case<br>        System.out.println(&quot;Collection is empty&quot;);<br>    }<br>}</pre><h3>Common Pitfalls to Avoid</h3><h4>1. Assuming All Collections Are Sequenced</h4><pre>// Wrong: Not all collections have well-defined encounter order<br>Set&lt;String&gt; regularSet = new HashSet&lt;&gt;(); // NOT sequenced<br>// regularSet.getFirst(); // This won&#39;t compile!<br><br>// Correct: Use collections with well-defined encounter order<br>SequencedSet&lt;String&gt; sequencedSet = new LinkedHashSet&lt;&gt;();<br>String first = sequencedSet.getFirst(); // This works</pre><h4>2. Forgetting About ConcurrentModificationException</h4><pre>// Dangerous: Modifying collection while iterating<br>SequencedCollection&lt;String&gt; items = new ArrayList&lt;&gt;(Arrays.asList(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;));<br>for (String item : items) {<br>    if (item.equals(&quot;b&quot;)) {<br>        items.removeFirst(); // May throw ConcurrentModificationException<br>    }<br>}<br><br>// Safe: Use iterator&#39;s remove method or collect items to remove<br>Iterator&lt;String&gt; iterator = items.iterator();<br>while (iterator.hasNext()) {<br>    String item = iterator.next();<br>    if (item.equals(&quot;b&quot;)) {<br>        iterator.remove(); // Safe removal<br>    }<br>}</pre><h3>Conclusion</h3><p>Sequenced Collections in Java 21 represent more than just a new API — they’re a paradigm shift toward consistency and developer productivity. By providing uniform operations across different collection types, they eliminate the cognitive overhead of remembering multiple APIs and reduce the likelihood of bugs.</p><p>As you migrate to Java 21, start by identifying places in your codebase where you’re accessing elements at the beginning or end of collections. These are prime candidates for leveraging the new sequenced interfaces. Your future self (and your teammates) will thank you for the cleaner, more maintainable code.</p><p>The introduction of Sequenced Collections demonstrates Java’s continued evolution toward developer-friendly APIs while maintaining backward compatibility. It’s these kinds of thoughtful improvements that keep Java relevant and productive for modern software development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8265c88528b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Eliminating NullPointerException Hell: Mastering the Null Object Pattern in Java]]></title>
            <link>https://medium.com/@tadeoaragoon/eliminating-nullpointerexception-hell-mastering-the-null-object-pattern-in-java-3af9cfd8eac1?source=rss-e126e053b725------2</link>
            <guid isPermaLink="false">https://medium.com/p/3af9cfd8eac1</guid>
            <category><![CDATA[advanced]]></category>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[null]]></category>
            <dc:creator><![CDATA[Tadeo Aragón]]></dc:creator>
            <pubDate>Wed, 30 Jul 2025 03:51:26 GMT</pubDate>
            <atom:updated>2025-07-30T03:51:26.864Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Ou_-2UWOdMu4gjqXj-A9A.png" /></figure><p>Have you ever spent hours debugging a production crash only to find the dreaded NullPointerException buried deep in your stack trace? You&#39;re not alone.</p><blockquote>The Problem That Keeps Developers Awake at Night</blockquote><p>Picture this scenario: You’re building an e-commerce application, and suddenly your production logs are flooded with NullPointerException errors. Users can&#39;t complete purchases, revenue is dropping, and your phone won&#39;t stop ringing. The culprit? Null references scattered throughout your codebase like hidden landmines.</p><pre>// This innocent-looking code is a ticking time bomb<br>public class OrderService {<br>    public void processOrder(Order order) {<br>        Customer customer = order.getCustomer(); // Could be null<br>        String email = customer.getEmail(); // BOOM! NullPointerException<br>        emailService.sendConfirmation(email);<br>    }<br>}</pre><p>The traditional approach involves defensive null checks everywhere, turning your elegant code into a maze of if-statements:</p><pre>public void processOrder(Order order) {<br>    if (order != null) {<br>        Customer customer = order.getCustomer();<br>        if (customer != null) {<br>            String email = customer.getEmail();<br>            if (email != null &amp;&amp; !email.isEmpty()) {<br>                emailService.sendConfirmation(email);<br>            }<br>        }<br>    }<br>}</pre><p>This approach works, but it’s verbose, error-prone, and makes your code harder to read and maintain. There’s a better way.</p><h3>Enter the Null Object Pattern</h3><p>The Null Object Pattern is a behavioral design pattern that provides a default object with neutral behavior instead of using null references. Instead of checking for null everywhere, you provide a special object that implements the same interface but does nothing or provides default behavior.</p><p>Think of it as having a “do-nothing” substitute that speaks the same language as your real objects.</p><h3>Core Implementation: Building Your First Null Object</h3><p>Let’s start with a practical example. Imagine you’re building a logging system where different environments might have different loggers:</p><pre>// Base interface<br>public interface Logger {<br>    void log(String message);<br>    void error(String message);<br>    boolean isEnabled();<br>}<br><br>// Real implementation<br>public class FileLogger implements Logger {<br>    private final String filename;<br>    <br>    public FileLogger(String filename) {<br>        this.filename = filename;<br>    }<br>    <br>    @Override<br>    public void log(String message) {<br>        // Write to file<br>        System.out.println(&quot;Writing to &quot; + filename + &quot;: &quot; + message);<br>    }<br>    <br>    @Override<br>    public void error(String message) {<br>        System.err.println(&quot;ERROR in &quot; + filename + &quot;: &quot; + message);<br>    }<br>    <br>    @Override<br>    public boolean isEnabled() {<br>        return true;<br>    }<br>}<br><br>// The Null Object - our star player<br>public class NullLogger implements Logger {<br>    @Override<br>    public void log(String message) {<br>        // Do nothing - but safely<br>    }<br>    <br>    @Override<br>    public void error(String message) {<br>        // Do nothing - but safely<br>    }<br>    <br>    @Override<br>    public boolean isEnabled() {<br>        return false; // Indicates it&#39;s a null object<br>    }<br>}</pre><p>Now your service can work without null checks:</p><pre>public class OrderService {<br>    private final Logger logger;<br>    <br>    public OrderService(Logger logger) {<br>        // No null check needed!<br>        this.logger = logger != null ? logger : new NullLogger();<br>    }<br>    <br>    public void processOrder(Order order) {<br>        logger.log(&quot;Processing order: &quot; + order.getId());<br>        <br>        // Business logic here<br>        <br>        logger.log(&quot;Order processed successfully&quot;);<br>        // No NullPointerException risk!<br>    }<br>}</pre><h3>Advanced Pattern: Smart Null Objects with State</h3><p>Let’s elevate this pattern with a more sophisticated example. Consider a notification system where different users have different notification preferences:</p><pre>public interface NotificationSender {<br>    void sendEmail(String message);<br>    void sendSMS(String message);<br>    void sendPushNotification(String message);<br>    NotificationStats getStats();<br>}<br><br>public class ActiveNotificationSender implements NotificationSender {<br>    private final String userId;<br>    private final NotificationStats stats;<br>    <br>    public ActiveNotificationSender(String userId) {<br>        this.userId = userId;<br>        this.stats = new NotificationStats();<br>    }<br>    <br>    @Override<br>    public void sendEmail(String message) {<br>        // Send actual email<br>        EmailService.send(userId, message);<br>        stats.incrementEmailsSent();<br>    }<br>    <br>    @Override<br>    public void sendSMS(String message) {<br>        // Send actual SMS<br>        SMSService.send(userId, message);<br>        stats.incrementSMSSent();<br>    }<br>    <br>    @Override<br>    public void sendPushNotification(String message) {<br>        // Send actual push notification<br>        PushService.send(userId, message);<br>        stats.incrementPushSent();<br>    }<br>    <br>    @Override<br>    public NotificationStats getStats() {<br>        return stats;<br>    }<br>}<br><br>// Smart Null Object that tracks what would have been sent<br>public class DisabledNotificationSender implements NotificationSender {<br>    private final NotificationStats stats;<br>    <br>    public DisabledNotificationSender() {<br>        this.stats = new NotificationStats();<br>    }<br>    <br>    @Override<br>    public void sendEmail(String message) {<br>        // Don&#39;t send, but track the attempt<br>        stats.incrementEmailsSkipped();<br>    }<br>    <br>    @Override<br>    public void sendSMS(String message) {<br>        stats.incrementSMSSkipped();<br>    }<br>    <br>    @Override<br>    public void sendPushNotification(String message) {<br>        stats.incrementPushSkipped();<br>    }<br>    <br>    @Override<br>    public NotificationStats getStats() {<br>        return stats; // Still provides useful information!<br>    }<br>}</pre><h3>Factory Pattern Integration: Making It Production-Ready</h3><p>Combine the Null Object Pattern with Factory Pattern for a robust solution:</p><pre>public class NotificationSenderFactory {<br>    private static final Map&lt;String, NotificationSender&gt; cache = <br>        new ConcurrentHashMap&lt;&gt;();<br>    <br>    public static NotificationSender createSender(UserPreferences preferences) {<br>        if (preferences == null || !preferences.isNotificationsEnabled()) {<br>            return new DisabledNotificationSender();<br>        }<br>        <br>        String userId = preferences.getUserId();<br>        return cache.computeIfAbsent(userId, <br>            id -&gt; new ActiveNotificationSender(id));<br>    }<br>    <br>    // Method to clear cache for testing or user preference updates<br>    public static void clearCache() {<br>        cache.clear();<br>    }<br>}<br><br>// Usage in your service<br>public class UserActionService {<br>    public void handleUserAction(User user, Action action) {<br>        NotificationSender sender = NotificationSenderFactory<br>            .createSender(user.getPreferences());<br>        <br>        // No null checks needed - works with both active and disabled senders<br>        sender.sendEmail(&quot;Action completed: &quot; + action.getDescription());<br>        <br>        // You can even get stats from disabled senders<br>        NotificationStats stats = sender.getStats();<br>        metricsService.record(stats);<br>    }<br>}</pre><h3>Performance Considerations and Thread Safety</h3><p>When implementing Null Objects in high-performance applications, consider these optimizations:</p><pre>public class OptimizedNullLogger implements Logger {<br>    // Singleton pattern for memory efficiency<br>    private static final OptimizedNullLogger INSTANCE = new OptimizedNullLogger();<br>    <br>    private OptimizedNullLogger() {} // Private constructor<br>    <br>    public static OptimizedNullLogger getInstance() {<br>        return INSTANCE;<br>    }<br>    <br>    @Override<br>    public void log(String message) {<br>        // Optimized: no operation, no object creation<br>    }<br>    <br>    @Override<br>    public void error(String message) {<br>        // Could still log critical errors even in &quot;null&quot; mode<br>        if (isCriticalError(message)) {<br>            System.err.println(&quot;CRITICAL: &quot; + message);<br>        }<br>    }<br>    <br>    @Override<br>    public boolean isEnabled() {<br>        return false;<br>    }<br>    <br>    private boolean isCriticalError(String message) {<br>        return message.contains(&quot;FATAL&quot;) || message.contains(&quot;SECURITY&quot;);<br>    }<br>}</pre><h3>Taking It to the Next Level: Advanced Techniques</h3><h3>1. Null Object with Strategy Pattern</h3><pre>public class AdaptiveNullObject implements Logger {<br>    private final LogLevel threshold;<br>    <br>    public AdaptiveNullObject(LogLevel threshold) {<br>        this.threshold = threshold;<br>    }<br>    <br>    @Override<br>    public void log(String message) {<br>        // Only log if above threshold<br>        if (LogLevel.INFO.ordinal() &gt;= threshold.ordinal()) {<br>            System.out.println(&quot;NULL-FILTERED: &quot; + message);<br>        }<br>    }<br>    <br>    @Override<br>    public void error(String message) {<br>        // Always log errors, even in null objects<br>        System.err.println(&quot;NULL-ERROR: &quot; + message);<br>    }<br>    <br>    @Override<br>    public boolean isEnabled() {<br>        return true; // It&#39;s enabled, but filtered<br>    }<br>}</pre><p>2. Null Object with Metrics Collection</p><pre>public class MetricsAwareNullObject implements NotificationSender {<br>    private final MetricsCollector metrics;<br>    private final AtomicLong suppressedNotifications = new AtomicLong();<br>    <br>    public MetricsAwareNullObject(MetricsCollector metrics) {<br>        this.metrics = metrics;<br>    }<br>    <br>    @Override<br>    public void sendEmail(String message) {<br>        long count = suppressedNotifications.incrementAndGet();<br>        metrics.gauge(&quot;notifications.suppressed.email&quot;, count);<br>    }<br>    <br>    @Override<br>    public void sendSMS(String message) {<br>        long count = suppressedNotifications.incrementAndGet();<br>        metrics.gauge(&quot;notifications.suppressed.sms&quot;, count);<br>    }<br>    <br>    @Override<br>    public void sendPushNotification(String message) {<br>        long count = suppressedNotifications.incrementAndGet();<br>        metrics.gauge(&quot;notifications.suppressed.push&quot;, count);<br>    }<br>    <br>    @Override<br>    public NotificationStats getStats() {<br>        return NotificationStats.builder()<br>            .suppressedCount(suppressedNotifications.get())<br>            .build();<br>    }<br>}</pre><h3>When NOT to Use the Null Object Pattern</h3><p>The pattern isn’t always the right choice. Avoid it when:</p><p><strong>The absence of an object is meaningful business logic</strong> (e.g., missing payment method should trigger specific handling)</p><p><strong>You need to distinguish between “object not found” and “object disabled”</strong></p><p><strong>The interface has many methods</strong> (leads to bloated null objects)</p><p><strong>Memory is extremely constrained</strong> (even lightweight null objects consume memory)</p><pre>// BAD: When null has semantic meaning<br>public class PaymentProcessor {<br>    public void processPayment(PaymentMethod method) {<br>        if (method == null) {<br>            // This null check has business meaning!<br>            redirectToPaymentMethodSelection();<br>            return;<br>        }<br>        // Process with actual method<br>    }<br>}</pre><h3>Key Takeaways</h3><p>The Null Object Pattern transforms your code from defensive to confident. Instead of constantly checking “is this null?”, you can focus on business logic knowing your objects will always respond appropriately.</p><p><strong>Benefits:</strong></p><ul><li>Eliminates NullPointerException risks</li><li>Reduces cyclomatic complexity</li><li>Makes code more readable and maintainable</li><li>Provides consistent behavior across your application</li></ul><p><strong>Remember:</strong></p><ul><li>Use singleton null objects when possible for memory efficiency</li><li>Consider smart null objects that provide useful default behavior</li><li>Combine with Factory Pattern for clean object creation</li><li>Don’t use when null has semantic business meaning</li></ul><p>The next time you’re tempted to add another null check, ask yourself: “Could I use a Null Object instead?” Your future self (and your production logs) will thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3af9cfd8eac1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Patterns that “wrap” objects]]></title>
            <link>https://medium.com/@tadeoaragoon/patterns-that-wrap-objects-1a3668f739d7?source=rss-e126e053b725------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a3668f739d7</guid>
            <category><![CDATA[objects]]></category>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[wrapped]]></category>
            <dc:creator><![CDATA[Tadeo Aragón]]></dc:creator>
            <pubDate>Sat, 21 Jun 2025 00:13:40 GMT</pubDate>
            <atom:updated>2025-06-21T00:20:33.342Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KelPtFpvouWPVs54-LnSjA.png" /></figure><p>When I first started learning design patterns, I often confused the Proxy, Facade, Decorator and Adapter patterns. Since all four are structural patterns that ‘wrap’ objects to modify their behavior, it’s easy to confuse them at first. However, with practice, the key differences become clear.</p><ol><li>Proxy: “Adds a control layer to manage access to an object.”</li><li>Facade: “Provides a simplified interface to hide a complex subsystem.”</li><li>Adapter: “Converts one interface into another to make incompatible classes work together.”</li><li>Decorator: “Adds new functionalities to objects.”</li></ol><p>Now, let’s explain each one:</p><h3>Facade</h3><p>A facade provides a interface that integrates a set of interfaces or classes to simplify a complex process. The client does not need to understand the underlying complexity and only requests the result of that process.</p><blockquote>purpuse: Simplified interface to a complex subsystem</blockquote><pre>// Complex subsystems<br>class CPU {<br>    void start() { System.out.println(&quot;CPU ON&quot;); }<br>}<br>class Memory {<br>    void load() { System.out.println(&quot;Memory loaded&quot;); }<br>}<br>class HardDrive {<br>    void read() { System.out.println(&quot;Reading disk&quot;); }<br>}<br><br>// Facade<br>class ComputerFacade {<br>    private CPU cpu;<br>    private Memory memory;<br>    private HardDrive hdd;<br><br>    public ComputerFacade() {<br>        this.cpu = new CPU();<br>        this.memory = new Memory();<br>        this.hdd = new HardDrive();<br>    }<br><br>    public void start() {<br>        cpu.start();<br>        memory.load();<br>        hdd.read();<br>        System.out.println(&quot;System ready!&quot;);<br>    }<br>}<br><br>// Usage:<br>ComputerFacade computer = new ComputerFacade();<br>computer.start(); // Client doesn&#39;t need to know about subsystems</pre><p>Key Characteristics:</p><ul><li>Creates a new, simpler interface</li><li>Knows about all subsystem components</li><li>Client communicates only with facade</li></ul><h3>Adapter</h3><p>An adapter provides an interface that bridges two incompatible interfaces, converting one into another. The client works with the adapter’s interface, while the adapter translates requests to the legacy or external system.</p><blockquote>Purpose: Interface conversion (like a USB-C to HDMI adapter)</blockquote><pre>// Old interface (incompatible)<br>class LegacyPrinter {<br>    void printDocument(String text) {<br>        System.out.println(&quot;Legacy printing: &quot; + text);<br>    }<br>}<br><br>// New interface (client expects this)<br>interface ModernPrinter {<br>    void print(String json);<br>}<br><br>// Adapter<br>class PrinterAdapter implements ModernPrinter {<br>    private LegacyPrinter legacyPrinter;<br><br>    public PrinterAdapter(LegacyPrinter printer) {<br>        this.legacyPrinter = printer;<br>    }<br><br>    public void print(String json) {<br>        // Convert JSON to plain text (adaptation logic)<br>        String text = &quot;Adapted: &quot; + json.replaceAll(&quot;[{}\&quot;]&quot;, &quot;&quot;);<br>        legacyPrinter.printDocument(text);<br>    }<br>}<br><br>// Usage:<br>ModernPrinter printer = new PrinterAdapter(new LegacyPrinter());<br>printer.print(&quot;{\&quot;text\&quot;:\&quot;Hello\&quot;}&quot;); <br><br>// Output: &quot;Legacy printing: Adapted: text:Hello&quot;</pre><p>Key Characteristics:</p><ul><li>Bridges two incompatible interfaces</li><li>Contains adaptation logic</li><li>Often wraps just one object</li></ul><h3>Proxy</h3><p>A proxy provides an interface that controls access to another object, acting as a substitute or placeholder. The client interacts with the proxy (as if it were the real object), while the proxy manages additional logic like lazy initialization, caching, or security checks.</p><blockquote>Purpose: Controlled access to an object (like a security guard or placeholder)</blockquote><pre>// Interface<br>interface Database {<br>    void query(String sql);<br>}<br><br>// Real object<br>class RealDatabase implements Database {<br>    public void query(String sql) {<br>        System.out.println(&quot;Executing: &quot; + sql);<br>    }<br>}<br><br>// Proxy (controls access)<br>class DatabaseProxy implements Database {<br>    private RealDatabase realDB;<br>    private boolean isAdmin;<br><br>    public DatabaseProxy(boolean isAdmin) {<br>        this.isAdmin = isAdmin;<br>    }<br><br>    public void query(String sql) {<br>        if (!isAdmin &amp;&amp; sql.contains(&quot;DELETE&quot;)) {<br>            throw new SecurityException(&quot;Permission denied&quot;);<br>        }<br>        <br>        if (realDB == null) { // Lazy initialization<br>            realDB = new RealDatabase();<br>        }<br>        <br>        realDB.query(sql); // Delegates to real object<br>    }<br>}<br><br>// Usage:<br>Database db = new DatabaseProxy(false);<br>db.query(&quot;SELECT * FROM users&quot;); // Works<br>db.query(&quot;DELETE FROM users&quot;);   // Throws exception</pre><p>Key Characteristics:</p><ul><li>Same interface as real object</li><li>Controls access (security, lazy loading, caching)</li><li>Often creates/manages the real object</li></ul><h3>Decorator</h3><p>A decorator wraps an object to add new behaviors or responsibilities without modifying its original interface. The client interacts with the decorated object as if it were the original, while the Decorator enhances its functionality transparently. This allows for flexible extensions at runtime, avoiding rigid subclassing.</p><blockquote>Purpuse: Dynamically add responsibilities to an object without subclassing</blockquote><pre>// Base Interface<br>interface Pizza {<br>    String getDescription();  // Returns pizza description<br>    double getPrice();        // Returns pizza price<br>}<br><br>// Concrete Pizza: Basic Pizza<br>class BasicPizza implements Pizza {<br>    @Override<br>    public String getDescription() {<br>        return &quot;Plain pizza&quot;;<br>    }<br><br>    @Override<br>    public double getPrice() {<br>        return 5.0;  // Base price<br>    }<br>}<br><br>// Abstract Decorator Class (implements Pizza)<br>abstract class PizzaDecorator implements Pizza {<br>    protected Pizza pizza;  // The Pizza object being decorated<br><br>    public PizzaDecorator(Pizza pizza) {<br>        this.pizza = pizza;<br>    }<br><br>    @Override<br>    public String getDescription() {<br>        return pizza.getDescription();<br>    }<br><br>    @Override<br>    public double getPrice() {<br>        return pizza.getPrice();<br>    }<br>}<br><br>// Concrete Decorator: Extra Cheese<br>class ExtraCheese extends PizzaDecorator {<br>    public ExtraCheese(Pizza pizza) {<br>        super(pizza);<br>    }<br><br>    @Override<br>    public String getDescription() {<br>        return pizza.getDescription() + &quot;, with extra cheese&quot;;<br>    }<br><br>    @Override<br>    public double getPrice() {<br>        return pizza.getPrice() + 2.0;<br>    }<br>}<br><br>// Usage Example:<br><br>// 1. Create a basic pizza<br> Pizza myPizza = new BasicPizza();<br> System.out.println(myPizza.getDescription() + &quot; | Price: $&quot; + myPizza.getPrice());<br>// Output: &quot;Plain pizza | Price: $5.0&quot;<br><br>// 2. Decorate it with extra cheese<br> myPizza = new ExtraCheese(myPizza);<br> System.out.println(myPizza.getDescription() + &quot; | Price: $&quot; + myPizza.getPrice());<br> // Output: &quot;Plain pizza, with extra cheese | Price: $7.0&quot;<br><br><br><br>    </pre><p>Key Characteristics:</p><ul><li>Same interface as the wrapped object</li><li>Adds/extends behavior dynamically</li><li>Transparent to the client</li></ul><p>I hope this information helps you differentiate between a Proxy, Facade,Adapter and Decorator patterns.<em> </em>There are other patterns, like Gateway, which may combine features of Proxy (intermediation) and Adapter (interface transformation), but serve a broader purpose: simplifying access to complex subsystems or external services, but i’ll cover those in another post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a3668f739d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Singleton Pattern and Enum Singleton]]></title>
            <link>https://medium.com/@tadeoaragoon/singleton-pattern-87d34f49f701?source=rss-e126e053b725------2</link>
            <guid isPermaLink="false">https://medium.com/p/87d34f49f701</guid>
            <category><![CDATA[critical-challenge]]></category>
            <category><![CDATA[easy-explanation]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[singleton-pattern]]></category>
            <dc:creator><![CDATA[Tadeo Aragón]]></dc:creator>
            <pubDate>Thu, 19 Jun 2025 20:54:46 GMT</pubDate>
            <atom:updated>2025-06-21T02:48:10.817Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eFznuiQtVmjqHPF0tOKK4A.png" /></figure><p>The Singleton pattern ensures that a class has only one instance and provides a global access point to that instance. It is commonly used for shared resources like database connections, thread pools, or configuration settings, where having multiple instances could cause security risks, performance issues, or inconsistent state.</p><h3>Football Ball Analogy</h3><p>In a soccer match, there’s only one ball in play at any given time (even if there are spare balls, logically only one is “active”).</p><h4>Why Singleton?</h4><ul><li>There should be only one instance of the soccer ball during the game.</li><li>All players (other objects in the system) must interact with the same ball.</li><li>If someone tries to create a “new ball,” the system should return the existing one</li></ul><h3>Java Implementation</h3><pre>public class SoccerBall {<br>    // The single instance of the ball (static + private)<br>    private static SoccerBall instance;<br>    private String status; // e.g., &quot;in play&quot;, &quot;out of bounds&quot;<br><br>    // Private constructor to prevent direct instantiation<br>    private SoccerBall() {<br>        this.status = &quot;in play&quot;; // Default state<br>    }<br><br>    // Global access point to the ball<br>    public static SoccerBall getInstance() {<br>        if (instance == null) {<br><br>            instance = new SoccerBall(); // Creates the ball if it <br>                                        //doesn&#39;t exist<br>        }<br>        return instance;<br>    }<br><br>    // Methods to interact with the ball<br>    public void kick() {<br>        System.out.println(&quot;Ball was kicked!&quot;);<br>    }<br><br>    public void setStatus(String status) {<br>        this.status = status;<br>    }<br><br>    public String getStatus() {<br>        return status;<br>    }<br>}</pre><h3>How It Works in the “Soccer Game” System</h3><pre>//All players share the same ball<br>SoccerBall ball1 = SoccerBall.getInstance();<br>SoccerBall ball2 = SoccerBall.getInstance();<br><br>System.out.println(ball1 == ball2); // true (same object)<br><br>//No duplicate balls can be created<br>//new SoccerBall() is impossible (constructor is private).<br><br>//Controlled state management<br>ball1.kick(); // &quot;Ball was kicked!&quot;  <br>ball1.setStatus(&quot;out of bounds&quot;);  <br>System.out.println(ball2.getStatus()); // &quot;out of bounds&quot; (shared state)  <br></pre><h3>Key Takeaways</h3><ul><li>Single source of truth: The ball’s state (position, status) is consistent across the entire system.</li><li>Global access: Any player/class can get the ball via SoccerBall.getInstance().</li><li>No duplicates: Ensures no &quot;illegal second ball&quot; is accidentally created.</li></ul><h3>When NOT to Use Singleton</h3><ul><li>If multiple balls could be in play (e.g., training session with many balls).</li><li>If the ball’s state doesn’t need to be shared.</li></ul><blockquote><em>The Singleton pattern is designed for classes that should only have one instance. If your application requires multiple instances of a class, then Singleton is not the appropriate pattern. To determine when to use Singleton, consider the soccer ball analogy: in a real match there can only be one official ball in play (Singleton), while during practice sessions multiple balls may be used simultaneously (regular class). When in doubt, ask yourself: ‘Does this scenario truly require a single, shared instance?</em></blockquote><h3>Common Problems and Pitfalls in Singleton Implementation and solutions</h3><p>While the Singleton pattern appears simple to implement, developers often overlook critical aspects that can lead to subtle bugs. Below are key challenges with their recommended solutions:</p><ol><li>Thread Safety Issues</li></ol><ul><li><em>Problem</em>: Multiple threads may create separate instances</li><li><em>Solution</em>: Use double-checked locking with volatile or static initialization.</li></ul><p>2. Reflection Vulnerabilities</p><ul><li><em>Problem</em>: Attackers can bypass private constructors</li><li><em>Solution</em>: Throw exception if constructor is called when instance exists</li></ul><p>3. Serialization Problems</p><ul><li><em>Problem</em>: Deserialization creates duplicate instances</li><li><em>Solution</em>: Implement readResolve() method</li></ul><p>4. Cloning Risks</p><ul><li><em>Problem</em>: clone() method can create copies</li><li><em>Solution</em>: Override clone() to throw CloneNotSupportedException</li></ul><p>5. Testing Difficulties</p><ul><li><em>Problem</em>: Global state makes unit testing challenging</li><li><em>Solution</em>: Consider dependency injection for testable design</li></ul><p>6. Memory Management</p><ul><li><em>Problem</em>: Static instance may never be garbage collected</li><li><em>Solution</em>: Use lazy initialization when appropriate</li></ul><pre>import java.io.Serializable;<br><br>/*<br> * Thread-safe Singleton implementation of a soccer ball<br> * with protection against reflection, serialization, and cloning attacks.<br> */<br>public final class SoccerBall implements Serializable {<br>    // volatile ensures visibility across threads<br>    private static volatile SoccerBall instance;<br>    private String status;<br><br>    // Private constructor with reflection protection<br>    private SoccerBall() {<br>        if (instance != null) {<br>          throw new IllegalStateException(&quot;Ball already exists! Use getInstance() instead.&quot;);<br>        }<br>        this.status = &quot;in play&quot;; // Default state<br>    }<br><br>    /**<br>     * Global access point using double-checked locking pattern<br>     * @return The single instance of SoccerBall<br>     */<br>    public static SoccerBall getInstance() {<br>        SoccerBall result = instance; // Local variable improves performance<br>        if (result == null) {<br>            synchronized (SoccerBall.class) {<br>                result = instance;<br>                if (result == null) {<br>                    instance = result = new SoccerBall();<br>                }<br>            }<br>        }<br>        return result;<br>    }<br><br>    // Ball behavior methods<br>    public void kick() {<br>        System.out.println(&quot;Ball was kicked!&quot;);<br>    }<br><br>    public void setStatus(String status) {<br>        this.status = status;<br>    }<br><br>    public String getStatus() {<br>        return status;<br>    }<br><br>    // Prevent serialization from creating new instances<br>    protected Object readResolve() {<br>        return getInstance();<br>    }<br><br>    // Prevent cloning<br>    @Override<br>    protected Object clone() throws CloneNotSupportedException {<br>        throw new CloneNotSupportedException(&quot;Singleton cannot be cloned&quot;);<br>    }<br>}</pre><h3>Enum Singleton</h3><p>The best way to implement this in Java? Using an enum, as recommended by Joshua Bloch (Java expert and author of <em>Effective Java</em>). Joshua Bloch introduced this approach in <em>Effective Java (Item 3: “Enforce the singleton property with a private constructor or an enum type”)</em> because:</p><ul><li>Guarantees a single instance (no duplicates, even with reflection or serialization).</li><li>Thread-safe by design (no race conditions in multi-threaded apps).</li><li>Simple and concise (no need for synchronized or double-checked locking).</li></ul><blockquote><em>“This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks.”</em><br> — Joshua Bloch, <em>Effective Java</em></blockquote><p><strong>Example: The Singleton Soccer Ball (</strong><strong>enum Implementation)</strong></p><pre>public enum SoccerBall {<br>    MATCH_BALL;  // The one and only instance!<br>    <br>    // Ball properties<br>    private String brand = &quot;Nike&quot;;<br>    private int airPressure = 9;  // Optimal PSI<br>    <br>    // Private constructor (runs only once)<br>    private SoccerBall() {<br>        System.out.println(&quot;The official match ball is ready!&quot;);<br>    }<br>    <br>    // Methods to interact with the ball<br>    public void kick() {<br>        System.out.println(&quot;The &quot; + brand + &quot; ball was kicked at &quot; + airPressure + &quot; PSI!&quot;);<br>    }<br>    <br>    public void adjustPressure(int newPressure) {<br>        this.airPressure = newPressure;<br>        System.out.println(&quot;Ball pressure updated to &quot; + airPressure + &quot; PSI.&quot;);<br>    }<br>}</pre><h3>Using the Ball in a Match (Client Code)</h3><pre>public class SoccerGame {<br>    public static void main(String[] args) {<br>        // All players use the same ball<br>        SoccerBall gameBall = SoccerBall.MATCH_BALL;<br>        <br>        gameBall.kick();  // &quot;The Nike ball was kicked at 9 PSI!&quot;<br>        <br>        // Referee adjusts pressure<br>        gameBall.adjustPressure(10);  // &quot; Ball pressure updated to 10 PSI.&quot;<br>        <br>        // Messi and Ronaldo share the same ball<br>        SoccerBall messisBall = SoccerBall.MATCH_BALL;<br>        SoccerBall ronaldosBall = SoccerBall.MATCH_BALL;<br>        <br>        System.out.println(&quot;Do Messi and Ronaldo use the same ball? &quot; + (messisBall == ronaldosBall));  // true <br>    }<br>}<br><br>/* <br>// ERROR: Not allowed! <br>SoccerBall fakeBall = new SoccerBall();  // Compilation error<br>*/</pre><p>I hope you’ve found this guide helpful for properly implementing the Singleton pattern. You now understand not just the basic structure, but also the critical challenges and how to solve them effectively. Remember: a well-implemented Singleton should be thread-safe, resistant to reflection and serialization, and easy to maintain.</p><blockquote>If you enjoyed this practical breakdown of the Singleton pattern using Java, you’ll find even more hands-on insights in:<br><a href="https://link.springer.com/book/10.1007/978-1-4842-7971-7">📘 <em>Java Design Patterns: A Hands-On Experience with Real-World Examples</em> by Vaskaran Sarcar</a></blockquote><blockquote><a href="http://www.youtube.com/watch?v=pi_I7oD_uGI#t=28m50s">🔗 Bloch’s <em>Effective Java</em> (Item 3) to master both classical and modern Java-specific pattern implementations.</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87d34f49f701" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Matching Pattern for java objects]]></title>
            <link>https://medium.com/@tadeoaragoon/matching-pattern-for-java-objects-aa9cb2905009?source=rss-e126e053b725------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa9cb2905009</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[matching]]></category>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[generics-programming]]></category>
            <dc:creator><![CDATA[Tadeo Aragón]]></dc:creator>
            <pubDate>Wed, 14 May 2025 04:53:41 GMT</pubDate>
            <atom:updated>2025-06-21T02:52:08.944Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZXXffojO_cVNRGqVNN-BzQ.png" /></figure><p>Extracting data from objects enables us to write <strong>concise, safe, and maintainable</strong> code, making it easier for other developers to understand and modify. Java has introduced <strong>pattern matching</strong> to simplify common coding tasks, particularly when working with object types and control structures. The two main features are:</p><ol><li>instanceof<strong> + Pattern Matching</strong> (Java 16+)</li><li>switch<strong> Pattern Matching</strong> (Java 17 preview, finalized in Java 21)</li></ol><h4>1. Pattern Matching with instanceof</h4><p>Before Java 16, type-checking and casting were separate steps:</p><pre>if (obj instanceof String) {<br>    String s = (String) obj; // Manual casting<br>    System.out.println(s.length());<br>}</pre><p><strong>With pattern matching (Java 16+):</strong></p><pre>if (obj instanceof String s) { // Auto-casting into &#39;s&#39;<br>    System.out.println(s.length()); // No explicit cast needed<br>}</pre><h4>2. Pattern Matching in switch (Java 21+)</h4><p>Java 21 finalized <strong>pattern matching for </strong>switch, allowing type-based branching without instanceof chains:</p><pre>if (shape instanceof Circle) {<br>    Circle c = (Circle) shape;<br>    System.out.println(&quot;Radius: &quot; + c.getRadius());<br>} else if (shape instanceof Rectangle) {<br>    Rectangle r = (Rectangle) shape;<br>    System.out.println(&quot;Area: &quot; + r.getWidth() * r.getHeight());<br>} else {<br>    System.out.println(&quot;Unknown shape&quot;);<br>}</pre><h4>Modern Approach (Java 21+)</h4><pre>switch (shape) {<br>    case Circle c -&gt; System.out.println(&quot;Radius: &quot; + c.getRadius());<br>    case Rectangle r -&gt; System.out.println(&quot;Area: &quot; + r.getWidth() * r.getHeight());<br>    default -&gt; System.out.println(&quot;Unknown shape&quot;);<br>}</pre><h4>3. Advanced Use Cases</h4><h4>3.1 Matching on null (Java 21+)</h4><pre>switch (obj) {<br>    case String s -&gt; System.out.println(&quot;String: &quot; + s);<br>    case null -&gt; System.out.println(&quot;Null object!&quot;); // Explicit null handling<br>    default -&gt; System.out.println(&quot;Other type&quot;);<br>}</pre><h4>3.2 Nested Patterns (Java 21+)</h4><pre>if (obj instanceof Point(int x, int y)) { // Deconstructing a record<br>    System.out.println(&quot;X: &quot; + x + &quot;, Y: &quot; + y);<br>}</pre><h4>3.3 Sealed Classes + Pattern Matching</h4><pre>sealed interface Shape permits Circle, Rectangle { }<br><br>record Circle(double radius) implements Shape { }<br>record Rectangle(double w, double h) implements Shape { }<br><br>// Exhaustive pattern matching (compiler checks all cases)<br>double area(Shape s) {<br>    return switch (s) {<br>        case Circle c -&gt; Math.PI * c.radius() * c.radius();<br>        case Rectangle r -&gt; r.w() * r.h();<br>    };<br>}</pre><blockquote>A sealed interface is an interface that restricts which classes or interfaces can implement it. This provides fine-grained control over inheritance hierarchies, improving API design and enabling safer pattern matching.</blockquote><h4>4. Generic types as operands</h4><p>The instanceof operator in Java can be used with generic types, but there are strict rules about which combinations are valid. These rules depend on the subtype relationship between the generic types and how they are parameterized.</p><p><strong>4.1 Direct Relationship (</strong><strong>ArrayList&lt;String&gt; → </strong><strong>List&lt;String&gt;)</strong></p><pre>List&lt;String&gt; stringList = new ArrayList&lt;&gt;();<br>if (stringList instanceof ArrayList&lt;String&gt;) {  // Valid<br>    System.out.println(&quot;ArrayList&lt;String&gt; detected&quot;);<br>}</pre><p><strong>Why it works</strong>:</p><ul><li>ArrayList&lt;String&gt; is a direct subtype of List&lt;String&gt;</li><li>Both the collection type (ArrayList) and generic parameter (String) match exactly</li></ul><p><strong>4.2 No Type Relationship — Invariance (Invalid)</strong></p><pre>List&lt;String&gt; stringList = new ArrayList&lt;&gt;();<br>if (stringList instanceof List&lt;CharSequence&gt;) {  // Compile error<br>    System.out.println(&quot;This will never work&quot;);<br>}</pre><p><strong>Why it fails</strong>:</p><ul><li>Although String extends CharSequence</li><li>Generics are invariant: List&lt;String&gt; is NOT a subtype of List&lt;CharSequence&gt;</li><li>Prevents unsafe additions of other CharSequence types</li></ul><p>The following code demonstrates why Java’s generic type invariance is necessary, showing what could go wrong if List&lt;String&gt; were incorrectly treated as a subtype of List&lt;CharSequence&gt;</p><pre>// Hypothetical dangerous scenario (doesn&#39;t actually compile)<br>List&lt;String&gt; stringList = new ArrayList&lt;&gt;();<br>stringList.add(&quot;Hello&quot;);<br><br>// If Java allowed this (which it doesn&#39;t):<br>List&lt;CharSequence&gt; charSeqList = stringList;  // ACTUALLY PROHIBITED BY COMPILER<br><br>// Then we could corrupt the original list:<br>charSeqList.add(new StringBuilder());  // Adding non-String to List&lt;String&gt;<br>String s = stringList.get(1);  // ClassCastException at runtime!<br><br>// This is why Java generics are invariant</pre><p><strong>4.3 Unbounded Wildcard (Valid)</strong></p><pre>List&lt;String&gt; stringList = new ArrayList&lt;&gt;();<br>if (stringList instanceof List&lt;?&gt;) {  // Valid<br>    System.out.println(&quot;Matches any List type&quot;);<br>}</pre><p><strong>Why it works</strong>:</p><ul><li>List&lt;?&gt; is supertype of all List&lt;T&gt; variants</li><li>Safe because it makes no assumptions about element type</li><li>Can only read as Object, can&#39;t add elements</li></ul><p><strong>4.4 Bounded Wildcard (Valid with restrictions)</strong></p><pre>List&lt;String&gt; stringList = new ArrayList&lt;&gt;();<br>if (stringList instanceof List&lt;? extends CharSequence&gt;) {  // Valid<br>    System.out.println(&quot;Matches CharSequence subtypes&quot;);<br>    CharSequence cs = stringList.get(0);  // Can read<br>    // stringList.add(&quot;new&quot;);  // Can&#39;t add (compile error)<br>}</pre><p><strong>Why it works</strong>:</p><ul><li>? extends CharSequence includes String and other subtypes</li><li>Safe for reading but not writing</li></ul><blockquote>Use extends to produce (get) and super to consume (add).</blockquote><p><strong>4.4 Raw Type (Valid but dangerous)</strong></p><pre>List&lt;String&gt; stringList = new ArrayList&lt;&gt;();<br>if (stringList instanceof List) {  // Valid but warning<br>    System.out.println(&quot;Raw type match&quot;);<br>    // Loses all generic type safety<br>}</pre><p><strong>Why it works but is bad</strong>:</p><ul><li>Backward compatibility with pre-Java 5 code</li><li>Bypasses generic type checking</li><li>Generates compiler warnings</li></ul><h4>Conclusion</h4><p>Pattern matching with instanceof and switch represents a natural evolution in Java, designed to:</p><ol><li><strong>Reduce Boilerplate Code</strong></li></ol><ul><li>Eliminates verbose type checks and manual casting.</li><li>Combines type testing and variable binding in a single step.</li></ul><p><strong>2. Enhance Code Safety &amp; Readability</strong></p><ul><li>Compile-time type verification prevents ClassCastException.</li><li>Clear, expressive syntax aligns with modern coding practices.</li></ul><p><strong>3. Future-Proof Your Designs</strong></p><ul><li>Seamlessly integrates with newer features like sealed classes and records</li><li>Prepares codebases for upcoming Java enhancements</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa9cb2905009" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>