<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>Java on YennJ12 Engineering Blog</title><link>https://yennj12.js.org/yennj12_blog_V4/tags/java/</link><description>Recent content in Java on YennJ12 Engineering Blog</description><generator>Hugo -- gohugo.io</generator><language>en-us</language><lastBuildDate>Mon, 25 May 2026 09:00:00 +0800</lastBuildDate><atom:link href="https://yennj12.js.org/yennj12_blog_V4/tags/java/feed.xml" rel="self" type="application/rss+xml"/><item><title>購物車系統的高並發改造（一）：Virtual Threads、HikariCP 與 Redis 快取三管齊下</title><link>https://yennj12.js.org/yennj12_blog_V4/posts/shopping-cart-high-concurrency-part1-zh/</link><pubDate>Sun, 24 May 2026 09:00:00 +0800</pubDate><guid>https://yennj12.js.org/yennj12_blog_V4/posts/shopping-cart-high-concurrency-part1-zh/</guid><description>前言 電商系統有一個非常典型的流量特徵：平時風平浪靜，一到促銷活動瞬間湧入幾千上萬個並發請求。
如果你的購物車系統跑在默認的 Spring Boot 設定上，這個瞬間幾乎必定會讓系統崩潰——不是 OOM，就是資料庫連線耗盡，要不然就是 Tomcat 執行緒池打滿、請求開始逾時。
這篇文章深入剖析我們在 PR #227 中對一個 Spring Boot 購物車系統進行的高並發改造，涵蓋三個核心技術方向：
JDK 21 Virtual Threads：讓每個請求都跑在輕量級虛擬執行緒上 HikariCP 連線池調校：消除資料庫連線成為瓶頸的問題 Redis 分層快取：把熱點讀取從資料庫移到記憶體 系統架構概述 先看清楚我們在改什麼。這是一個標準的 Spring Boot 電商後端：
Client (Web/App) ↓ HTTP Spring Boot API (port 9999) ├── CartController → CartService → MySQL (cart table) ├── ProductController → ProductService → MySQL (products table) ├── OrderController → OrderService → MySQL (orders/order_items) │ → Stripe API (付款) ├── UserController → UserService → MySQL (users) └── AuthController → AuthenticationService → MySQL (auth_tokens) 技術棧：Spring Boot 3.</description></item><item><title>購物車系統的高並發改造（二）：Redisson 分散式鎖、讀寫分離路由與 Docker HA 水平擴展</title><link>https://yennj12.js.org/yennj12_blog_V4/posts/shopping-cart-high-concurrency-part2-zh/</link><pubDate>Mon, 25 May 2026 09:00:00 +0800</pubDate><guid>https://yennj12.js.org/yennj12_blog_V4/posts/shopping-cart-high-concurrency-part2-zh/</guid><description>前言 第一篇解決了系統的吞吐量問題：Virtual Threads 讓執行緒不再阻塞在 I/O 上，HikariCP 調校讓資料庫連線不再是瓶頸，Redis 快取讓熱點讀取從記憶體直接回傳。
但吞吐量提升後，反而暴露出一個更深層的問題：
並發請求同時寫入同一份資料，怎麼保證正確性？
想像雙十一活動開始的那一秒，同一個用戶的兩個 Tab 同時按下「加入購物車」；或者同一個人網路不穩，重試了兩次「立即結帳」——這兩種場景都會導致重複訂單或資料不一致。
這篇介紹 PR #228 帶來的三個進階改造：
Redisson 分散式鎖：防止同一用戶的並發寫入互相干擾 讀寫分離路由：把讀請求分流到 Replica，Primary 只處理寫入 Docker HA 水平擴展：Nginx + 多個 App 實例 + MySQL 主從複製 方案四：Redisson 分散式鎖 為什麼需要分散式鎖？ 第一篇的 CartService.addToCart() 在高並發下有一個隱患：
1// Part 1 的版本（沒有鎖） 2public void addToCart(AddToCartDto addToCartDto, Product product, User user) { 3 Cart cart = new Cart(product, addToCartDto.getQuantity(), user); 4 cartRepository.save(cart); // ← 多個執行緒可能同時執行這一行 5} 當同一個用戶同時發出兩個「加入購物車」請求時：
Thread A: new Cart(productX, qty=1, user) → save → 購物車有 1 個 productX Thread B: new Cart(productX, qty=1, user) → save → 購物車有 2 個 productX（重複！） cartRepository.</description></item><item><title>Java Concurrency Deep Dive Part 2: Mastering Runnable, Callable Patterns and Internal Mechanisms</title><link>https://yennj12.js.org/yennj12_blog_V4/posts/java-concurrency-deep-dive-runnable-callable-patterns-part2/</link><pubDate>Tue, 28 Jan 2025 03:00:00 +0800</pubDate><guid>https://yennj12.js.org/yennj12_blog_V4/posts/java-concurrency-deep-dive-runnable-callable-patterns-part2/</guid><description>🎯 Introduction Building upon our comprehensive overview of Java concurrency, this deep dive explores the fundamental building blocks that power Java&amp;rsquo;s threading mechanisms. We&amp;rsquo;ll dissect the internals of Runnable and Callable interfaces, examine thread synchronization primitives, understand the Java Memory Model, and explore advanced patterns that form the foundation of robust concurrent applications.
This technical deep dive is essential for developers who want to understand not just how to use Java&amp;rsquo;s concurrency tools, but how they work under the hood and how to leverage them effectively in complex scenarios.</description></item><item><title>Java Concurrency Part 3: Design Patterns with Thread Interfaces - Producer-Consumer, Observer, and Enterprise Patterns</title><link>https://yennj12.js.org/yennj12_blog_V4/posts/java-concurrency-design-patterns-thread-interfaces-part3/</link><pubDate>Tue, 28 Jan 2025 04:00:00 +0800</pubDate><guid>https://yennj12.js.org/yennj12_blog_V4/posts/java-concurrency-design-patterns-thread-interfaces-part3/</guid><description>🎯 Introduction Building upon our deep dive into Java concurrency fundamentals, this third part explores how classic design patterns can be elegantly implemented using thread interfaces. We&amp;rsquo;ll examine how Runnable, Callable, and other concurrency primitives can be combined with design patterns to create robust, scalable, and maintainable concurrent systems.
This guide demonstrates practical implementations of essential design patterns in concurrent environments, showing how threading interfaces enhance traditional patterns while addressing the unique challenges of multi-threaded programming.</description></item><item><title>AWS DynamoDB Complete Guide: Architecture, Indexing &amp; Performance Optimization</title><link>https://yennj12.js.org/yennj12_blog_V4/posts/aws-dynamodb-complete-guide-optimization/</link><pubDate>Mon, 29 Sep 2025 10:02:35 +0800</pubDate><guid>https://yennj12.js.org/yennj12_blog_V4/posts/aws-dynamodb-complete-guide-optimization/</guid><description>Introduction Amazon DynamoDB is a fully managed NoSQL database service that provides fast and predictable performance with seamless scalability. This comprehensive guide explores DynamoDB&amp;rsquo;s architecture, data structures, indexing strategies, and advanced optimization techniques to achieve maximum performance for your applications.
DynamoDB Architecture Overview Core Architecture Components graph TB subgraph &amp;#34;DynamoDB Service Architecture&amp;#34; APP[Application Layer] SDK[AWS SDK] API[DynamoDB API] subgraph &amp;#34;DynamoDB Core&amp;#34; AUTH[Authentication &amp;amp; Authorization] ROUTER[Request Router] METADATA[Metadata Service] subgraph &amp;#34;Storage Layer&amp;#34; PARTITION1[Partition 1] PARTITION2[Partition 2] PARTITION3[Partition 3] PARTITIONN[Partition N] end subgraph &amp;#34;Index Layer&amp;#34; GSI[Global Secondary Indexes] LSI[Local Secondary Indexes] end end subgraph &amp;#34;Infrastructure&amp;#34; SSD[SSD Storage] REPLICATION[Multi-AZ Replication] BACKUP[Automated Backups] end end APP --&amp;gt; SDK SDK --&amp;gt; API API --&amp;gt; AUTH AUTH --&amp;gt; ROUTER ROUTER --&amp;gt; METADATA ROUTER --&amp;gt; PARTITION1 ROUTER --&amp;gt; PARTITION2 ROUTER --&amp;gt; PARTITION3 ROUTER --&amp;gt; PARTITIONN PARTITION1 --&amp;gt; SSD PARTITION2 --&amp;gt; SSD PARTITION3 --&amp;gt; SSD PARTITIONN --&amp;gt; SSD SSD --&amp;gt; REPLICATION REPLICATION --&amp;gt; BACKUP DynamoDB vs Traditional Databases Feature DynamoDB Traditional RDBMS MongoDB Data Model Key-Value &amp;amp; Document Relational Tables Document Schema Schema-less Fixed Schema Flexible Schema Scaling Horizontal (Auto) Vertical (Manual) Horizontal (Manual) Consistency Eventually Consistent ACID Transactions Configurable Query Language PartiQL &amp;amp; APIs SQL MongoDB Query Language Performance Single-digit millisecond Variable Variable Management Fully Managed Self-Managed Self/Managed Options DynamoDB Data Structures Primary Key Structures DynamoDB supports two types of primary keys:</description></item><item><title>JVM 記憶體深度解析：堆疊與堆積記憶體完整指南</title><link>https://yennj12.js.org/yennj12_blog_V4/posts/jvm-memory-heap-stack-comprehensive-guide-zh/</link><pubDate>Mon, 29 Sep 2025 09:50:40 +0800</pubDate><guid>https://yennj12.js.org/yennj12_blog_V4/posts/jvm-memory-heap-stack-comprehensive-guide-zh/</guid><description>前言 Java 虛擬機器（JVM）的記憶體管理是 Java 應用程式效能的核心關鍵。本文將深入探討 JVM 記憶體結構，特別是堆疊（Stack）與堆積（Heap）記憶體的運作機制，並提供實際的程式碼範例與最佳化策略。
JVM 記憶體結構概覽 JVM 記憶體主要分為以下幾個區域：
graph TB subgraph &amp;#34;JVM 記憶體區域&amp;#34; PC[程式計數器&amp;lt;br/&amp;gt;Program Counter] STACK[虛擬機器堆疊&amp;lt;br/&amp;gt;VM Stack] NATIVE[本地方法堆疊&amp;lt;br/&amp;gt;Native Method Stack] HEAP[堆積記憶體&amp;lt;br/&amp;gt;Heap Memory] METHOD[方法區&amp;lt;br/&amp;gt;Method Area] DIRECT[直接記憶體&amp;lt;br/&amp;gt;Direct Memory] end subgraph &amp;#34;堆積記憶體詳細結構&amp;#34; YOUNG[年輕世代&amp;lt;br/&amp;gt;Young Generation] OLD[老年世代&amp;lt;br/&amp;gt;Old Generation] subgraph &amp;#34;年輕世代細分&amp;#34; EDEN[Eden 區] S0[Survivor 0] S1[Survivor 1] end end HEAP --&amp;gt; YOUNG HEAP --&amp;gt; OLD YOUNG --&amp;gt; EDEN YOUNG --&amp;gt; S0 YOUNG --&amp;gt; S1 JVM 記憶體區域比較表 記憶體區域 執行緒共享 生命週期 主要用途 GC 影響 程式計數器 否 執行緒生命週期 記錄當前執行指令位置 無 虛擬機器堆疊 否 執行緒生命週期 方法調用與局部變數 無 本地方法堆疊 否 執行緒生命週期 本地方法調用 無 堆積記憶體 是 JVM 生命週期 物件實例與陣列 是 方法區 是 JVM 生命週期 類別資訊與常數池 部分 直接記憶體 是 手動管理 NIO 操作緩衝區 無 堆疊記憶體（Stack Memory）深度解析 堆疊記憶體的特性 堆疊記憶體是每個執行緒獨有的記憶體區域，採用 LIFO（Last In First Out）的結構。</description></item><item><title>Spring Boot 程式碼載入深度解析：從編譯到物件實例化完整流程</title><link>https://yennj12.js.org/yennj12_blog_V4/posts/spring-boot-code-loading-compilation-transformation-zh/</link><pubDate>Mon, 29 Sep 2025 09:50:40 +0800</pubDate><guid>https://yennj12.js.org/yennj12_blog_V4/posts/spring-boot-code-loading-compilation-transformation-zh/</guid><description>前言 Spring Boot 應用程式的啟動過程涉及複雜的程式碼載入、編譯轉換和物件實例化機制。本文將詳細分析從 Java 原始碼到執行期物件的完整轉換流程，幫助開發者深入理解 Spring Boot 的底層運作原理。
Java 程式碼編譯與載入流程 編譯階段：從原始碼到位元組碼 graph TB subgraph &amp;#34;編譯階段&amp;#34; JAVA[Java 原始碼&amp;lt;br/&amp;gt;.java 檔案] JAVAC[javac 編譯器] CLASS[位元組碼檔案&amp;lt;br/&amp;gt;.class 檔案] JAR[打包成 JAR&amp;lt;br/&amp;gt;.jar 檔案] end subgraph &amp;#34;載入階段&amp;#34; CLASSLOADER[類別載入器&amp;lt;br/&amp;gt;ClassLoader] JVM_MEMORY[JVM 記憶體區域] METHOD_AREA[方法區&amp;lt;br/&amp;gt;Class 資訊] HEAP[堆積記憶體&amp;lt;br/&amp;gt;物件實例] end JAVA --&amp;gt; JAVAC JAVAC --&amp;gt; CLASS CLASS --&amp;gt; JAR JAR --&amp;gt; CLASSLOADER CLASSLOADER --&amp;gt; JVM_MEMORY JVM_MEMORY --&amp;gt; METHOD_AREA JVM_MEMORY --&amp;gt; HEAP Java 編譯過程詳解 1/** 2 * Java 編譯過程示例 3 * 從原始碼到位元組碼的轉換 4 */ 5public class CompilationProcessDemo { 6 7 // 1.</description></item><item><title>AWS VPC Complete Guide: Enterprise Networking Patterns &amp; VPC Peering</title><link>https://yennj12.js.org/yennj12_blog_V4/posts/aws-vpc-complete-guide-enterprise-networking/</link><pubDate>Mon, 29 Sep 2025 08:35:54 +0800</pubDate><guid>https://yennj12.js.org/yennj12_blog_V4/posts/aws-vpc-complete-guide-enterprise-networking/</guid><description>Introduction Amazon Virtual Private Cloud (VPC) is the foundation of AWS networking, providing isolated virtual networks within the AWS cloud. This guide explores VPC types, enterprise network design patterns, VPC peering strategies, and practical Java implementations for production environments.
AWS VPC Fundamentals What is AWS VPC? AWS VPC lets you provision a logically isolated section of the AWS Cloud where you can launch AWS resources in a virtual network that you define.</description></item><item><title>AWS Load Balancers: Complete Guide - Application, Network, Gateway, and Classic Load Balancers Comparison with Implementation</title><link>https://yennj12.js.org/yennj12_blog_V4/posts/aws-load-balancer-complete-guide-comparison/</link><pubDate>Mon, 29 Sep 2025 08:28:29 +0800</pubDate><guid>https://yennj12.js.org/yennj12_blog_V4/posts/aws-load-balancer-complete-guide-comparison/</guid><description>🎯 Introduction AWS Load Balancers are critical components for building highly available, fault-tolerant, and scalable applications in the cloud. They distribute incoming traffic across multiple targets, ensuring optimal resource utilization and system reliability. This comprehensive guide explores all AWS Load Balancer types, their unique features, and when to use each one for maximum effectiveness.
Understanding the nuances between Application Load Balancer (ALB), Network Load Balancer (NLB), Gateway Load Balancer (GWLB), and Classic Load Balancer (CLB) is essential for architecting robust cloud solutions that can handle varying traffic patterns and requirements.</description></item><item><title>AWS API Gateway: Complete Guide with Load Balancer Comparison, Microservices Architecture, and Java Implementation</title><link>https://yennj12.js.org/yennj12_blog_V4/posts/aws-api-gateway-comprehensive-guide-comparison/</link><pubDate>Mon, 29 Sep 2025 08:19:47 +0800</pubDate><guid>https://yennj12.js.org/yennj12_blog_V4/posts/aws-api-gateway-comprehensive-guide-comparison/</guid><description>🎯 Introduction In modern distributed systems with dozens or hundreds of microservices, managing API traffic becomes increasingly complex. AWS API Gateway emerges as a critical component that acts as a single entry point for all client requests, solving major challenges in microservices architecture. This comprehensive guide explores API Gateway fundamentals, compares it with load balancers, and provides production-ready Java implementations.
API Gateway transforms chaotic microservices communication into organized, secure, and scalable architecture patterns that are essential for enterprise-grade applications.</description></item><item><title>Webhooks: Complete Guide with Java Implementation - Event-Driven Architecture, Real-Time Integrations, and Best Practices</title><link>https://yennj12.js.org/yennj12_blog_V4/posts/webhooks-comprehensive-guide-java-implementation/</link><pubDate>Mon, 29 Sep 2025 08:06:11 +0800</pubDate><guid>https://yennj12.js.org/yennj12_blog_V4/posts/webhooks-comprehensive-guide-java-implementation/</guid><description>🎯 Introduction Webhooks are HTTP callbacks that enable real-time, event-driven communication between applications. Instead of continuously polling for updates, webhooks allow systems to push data immediately when events occur. This comprehensive guide explores webhook architecture, compares different integration approaches, and provides production-ready Java implementations with real-world examples from Stripe, Shopify, and GitHub.
Webhooks have become essential for modern distributed systems, enabling efficient, scalable, and responsive integrations that power everything from payment processing to CI/CD pipelines and e-commerce automation.</description></item><item><title>Redis Sentinel: Complete High Availability Setup Guide with Java Integration and Monitoring</title><link>https://yennj12.js.org/yennj12_blog_V4/posts/redis-sentinel-high-availability-setup-guide/</link><pubDate>Mon, 29 Sep 2025 07:54:22 +0800</pubDate><guid>https://yennj12.js.org/yennj12_blog_V4/posts/redis-sentinel-high-availability-setup-guide/</guid><description>🎯 Introduction Redis Sentinel provides high availability and monitoring for Redis deployments. It&amp;rsquo;s a distributed system that monitors Redis master and replica instances, performs automatic failover, and acts as a configuration provider for clients. This comprehensive guide covers Redis Sentinel architecture, setup procedures, Java integration, and production best practices.
Redis Sentinel solves critical production challenges including automatic failover, service discovery, and configuration management, making it essential for mission-critical applications that require high availability and minimal downtime.</description></item><item><title>Essential Design Patterns in Java: A Comprehensive Guide to Creational, Structural, and Behavioral Patterns</title><link>https://yennj12.js.org/yennj12_blog_V4/posts/essential-design-patterns-java-comprehensive-guide/</link><pubDate>Mon, 29 Sep 2025 07:45:06 +0800</pubDate><guid>https://yennj12.js.org/yennj12_blog_V4/posts/essential-design-patterns-java-comprehensive-guide/</guid><description>🎯 Introduction Design patterns are proven solutions to commonly occurring problems in software design. They represent best practices evolved over time and provide a shared vocabulary for developers. This comprehensive guide explores the most essential design patterns in Java, demonstrating practical implementations with real-world examples.
We&amp;rsquo;ll cover the three main categories of design patterns from the Gang of Four: Creational, Structural, and Behavioral patterns, showing how to implement them effectively in modern Java applications.</description></item><item><title>Building a Spotify Playlist Application with Spring Boot and Vue.js</title><link>https://yennj12.js.org/yennj12_blog_V4/posts/spotify-playlist-full-stack-application/</link><pubDate>Sat, 06 Sep 2025 14:13:59 +0800</pubDate><guid>https://yennj12.js.org/yennj12_blog_V4/posts/spotify-playlist-full-stack-application/</guid><description>使用 Spring Boot 後端與 Vue.js 前端，整合 Spotify API 打造智能音樂推薦系統，突破 Spotify 原生推薦限制，提供更主動的音樂探索體驗。</description></item><item><title>Java Concurrency and Threading: Complete Guide to Runnable, Callable, and Modern Thread Patterns</title><link>https://yennj12.js.org/yennj12_blog_V4/posts/java-concurrency-threading-runnable-callable-guide/</link><pubDate>Tue, 28 Jan 2025 02:00:00 +0800</pubDate><guid>https://yennj12.js.org/yennj12_blog_V4/posts/java-concurrency-threading-runnable-callable-guide/</guid><description>🎯 Introduction Concurrency and threading are fundamental aspects of modern Java applications, enabling programs to perform multiple tasks simultaneously and efficiently utilize system resources. As applications become more complex and performance requirements increase, understanding Java&amp;rsquo;s threading mechanisms becomes crucial for building scalable, responsive applications.
This comprehensive guide explores Java&amp;rsquo;s concurrency landscape, from basic threading concepts to advanced patterns, providing practical implementations and performance insights for enterprise applications.
🧵 Java Threading Fundamentals 🔍 Understanding Threads and Concurrency A thread is a lightweight sub-process that allows concurrent execution of multiple tasks within a single program.</description></item><item><title>SAGA Pattern: Managing Distributed Transactions in Spring Boot Microservices</title><link>https://yennj12.js.org/yennj12_blog_V4/posts/saga-pattern-distributed-transactions-spring-boot/</link><pubDate>Tue, 28 Jan 2025 01:00:00 +0800</pubDate><guid>https://yennj12.js.org/yennj12_blog_V4/posts/saga-pattern-distributed-transactions-spring-boot/</guid><description>🎯 Introduction In the era of microservices architecture, managing transactions across multiple services presents significant challenges. Traditional distributed transaction mechanisms like Two-Phase Commit (2PC) often lead to tight coupling, reduced availability, and poor performance. The SAGA Pattern emerges as a powerful alternative, providing a way to manage distributed transactions through a sequence of local transactions, each with compensating actions for rollback scenarios.
📚 What is the SAGA Pattern? 🔍 Core Concepts The SAGA pattern is a design pattern for managing long-running distributed transactions across multiple microservices.</description></item><item><title>Data Consistency Patterns in Java Enterprise Applications</title><link>https://yennj12.js.org/yennj12_blog_V4/posts/data-consistency-patterns-java-enterprise-applications/</link><pubDate>Tue, 28 Jan 2025 00:00:00 +0800</pubDate><guid>https://yennj12.js.org/yennj12_blog_V4/posts/data-consistency-patterns-java-enterprise-applications/</guid><description>🎯 Introduction Data consistency is one of the most critical challenges in modern Java enterprise applications. As systems scale and become distributed, maintaining data integrity while ensuring performance becomes increasingly complex. This comprehensive guide explores practical data consistency patterns implemented in real-world Java applications, complete with case studies, implementation details, and detailed trade-off analysis.
📊 The Data Consistency Challenge 🔍 Understanding Data Consistency Levels Data consistency refers to the guarantee that all nodes in a distributed system see the same data at the same time.</description></item></channel></rss>