Understanding the Non-Blocking Synchronization Mechanism of Optimistic Locking CAS

In the world of concurrent programming, “thread safety” usually means “locking”. From the synchronized keyword to ReentrantLock, we’ve grown accustomed to ensuring data consistency by exclusively locking resources. However, locks are not a silver bullet. In scenarios pursuing extreme performance, the context switching and waiting costs brought by locks can become system bottlenecks. So, is there a way to safely modify shared variables across multiple threads without suspending (blocking) threads? ...

December 7, 2025 · 6 min

Understanding and Applying Java Generics

1. Overview Generics sanitize your code by providing: Safety: Compile-time type checking. Reusability: Using <T> for generic structures. Cleanliness: Reducing boilerplate casting. Java generics are implemented via Type Erasure, meaning the type information exists only during compilation to ensure backward compatibility. 2. Basic Evolution Concrete Types: IntList only handles integers. Object Container: ObjectList handles everything but requires non-safe casting. Generics: GenericList<T> handles everything with full type safety. 3. Tuples: Simple Data Objects When you need to return multiple values of different types without a dedicated POJO: ...

May 24, 2023 · 2 min

Understanding and Applying Java Reflection

1. Overview Reflection allows a Java program to inspect or manipulate its own internal structure at runtime. It can access class names, fields, methods, and constructors without knowing them at compile time. 2. Why Reflection? Dynamic Loading: Class.forName(name) allows loading plugins or drivers at runtime. Dynamic Invocation: Frameworks like Spring use it to call methods on Bean instances. Generic Inspection: Writing code that can work with any object (e.g., serializing a JSON string). 3. Usage Scenarios Frameworks: Spring (Dependency Injection), JUnit (finding @Test methods). ORM: Hibernate/MyBatis mapping DB rows to POJO fields. Dynamic Proxy: Routing method calls at runtime. Unit Testing: Accessing private fields or methods for validation. 4. The Class Object The java.lang.Class object is the entry point. Ways to get it: ...

May 21, 2023 · 2 min

Reflections on Java Exception Handling

1. Classification of Java Exceptions Java exceptions are basically divided into two categories: Checked Exceptions and Unchecked Exceptions (Runtime Exceptions). Checked Exceptions These are exceptions that the compiler forces you to handle (either via try-catch or throws). They usually represent external factors that the program cannot control, such as a file not being found or a network interruption. Unchecked Exceptions (Runtime Exceptions) These occur during the execution of the program, such as NullPointerException, ArrayIndexOutOfBoundsException, or IllegalArgumentException. They usually indicate programming errors or logic flaws. ...

May 18, 2023 · 2 min

Guide to java.nio.file Library in Java

Introduction Before Java 7, file handling was primarily done through java.io.File, which lacked support for symbolic links, modern file systems, and efficient recursive operations. The java.nio.file package (NIO.2) introduced in Java 7 solved these issues with a more comprehensive and powerful API. Core Components 1. Path The Path interface represents a hierarchical path to a file or directory. Unlike File, it is system-independent. Path path = Paths.get("data", "logs", "app.log"); // On Windows: data\logs\app.log // On Linux: data/logs/app.log 2. Files Utility The Files class contains static methods for almost any file operation: ...

May 9, 2023 · 2 min

Several Reference Suggestions for Improving Code Quality

Unit Testing What is Unit Testing? Unit testing usually refers to testing a single function or method. The purpose of unit testing is to verify whether the behavior of each unit meets expectations and to quickly detect any potential problems when modifying the code. By writing test cases, we can verify whether these modules produce the correct output for specific inputs. The goal is to ensure that each module runs normally in various situations. ...

April 25, 2023 · 4 min

Introduction to Java Stream Programming

What is a Stream? A Stream is a sequence of elements supporting sequential and parallel aggregate operations. It focuses on the “what” (declarative) rather than the “how” (imperative). Key Characteristics: No Storage: Streams don’t store data; they move it from a source (collection, array, I/O) through a pipeline. Functional: Operations don’t modify the source; they return new streams. Lazy Evaluation: Intermediate operations are only performed when a terminal operation is called. Possibly Infinite: Unlike collections, streams can be unbounded (e.g., a stream of random numbers). Stream Pipeline Stages Creation: list.stream(), Stream.of(a, b), IntStream.range(1, 10). Intermediate Operations: (Lazy) filter, map, sorted, distinct. Terminal Operations: (Triggers execution) collect, forEach, reduce, count, anyMatch. Common Operations Creation Stream.generate(Math::random).limit(10) Stream.iterate(0, n -> n + 2).limit(5) (Generates 0, 2, 4, 6, 8) Intermediate filter(Predicate): Selects elements. map(Function): Transforms elements. flatMap(Function): Flattens a stream of streams into a single stream. peek(Consumer): Performs an action for each element (mainly for debugging). Terminal collect(Collectors.toList()): Accumulates elements into a collection. reduce(BinaryOperator): Combines elements into a single result (e.g., sum). allMatch/anyMatch/noneMatch: Returns a boolean based on a condition. The Optional Class Many terminal operations return an Optional<T> to avoid NullPointerException if the stream is empty. ...

April 6, 2023 · 2 min

Introduction to Java Lambda Functional Programming

Overview Functional programming is based on Lambda Calculus, a formal system for studying functions developed by Alonzo Church in the 1930s. Languages like Haskell and Erlang brought these concepts into practical use. Java 8 introduced these features to handle growing program complexity through a more concise and robust style. OO is about abstracting data; FP is about abstracting behavior. Traditional vs. Lambda Style Before Java 8, we used anonymous inner classes for strategies or callbacks. This was verbose. ...

April 2, 2023 · 2 min

Microservice Design Principles Based on Spring Cloud

1. The Core Philosophy The shift from monolith to microservices is like moving from a “battleship” to a “fleet.” Breaking down a large application into small, independent services provides: Agility: Rapid deployment cycles. Resilience: Fault isolation (one service crash doesn’t kill the whole app). Scalability: Scaling only the bottleneck services. 2. The Cost of Decentralization Microservices are not a solution for everyone. They introduce: Network Latency: Inter-service calls are slower than in-memory calls. Data Consistency: Distributed transactions are complex (CAP Theorem). Operational Complexity: You need robust monitoring and logging. 3. Spring Cloud Ecosystem Spring Cloud provides a suite of tools for the common “pain points” of microservices: ...

September 14, 2020 · 2 min