Skip to main content

Log4j2 Logging Levels – Complete Guide

Imagine your application's log file as a constant stream of information. In a production crisis, this stream becomes a firehose. How do you find the single critical error message in a flood of routine status updates? The answer lies in logging levels. These aren't just labels; they are the fundamental control mechanism in Log4j2. They allow developers to filter noise, pinpoint failures, and monitor application health effectively. Mastering this hierarchy is the key to creating logs that are helpful, not overwhelming. This guide explores Log4j2’s levels, from configuration to real-world best practices. The Logging Threshold: How Levels Work Think of logging levels as a gatekeeper's volume knob. Each log message you write (an "event") is assigned a level of importance, or severity. The logger itself is then configured with a threshold level. When a message arrives, the framework compares its severity to the logger's threshold. Only messages at or above the configured threshold are processed and sent to their destination (like a file or the console). This simple mechanism provides fine-grained control over your application's verbosity. You can run the exact same code in different environments and get drastically different log outputs—all without changing a single line of Java. In development, you might set the threshold low to see everything. In production, you set it high to capture only significant errors.

Understanding JUnit 5 @AfterEach Annotation with Practical Examples

In the world of Java development, writing a test is only half the battle. The real challenge lies in ensuring those tests are isolated, repeatable, and clean. If your first test leaves a database connection open, a locked file in the filesystem, or a messy entry in a shared cache, your second test might fail—not because of a bug in your production code, but because of a "dirty" environment. These "flaky tests" are the bane of modern CI/CD pipelines, leading to wasted developer time and decreased confidence in the build. This is where the JUnit 5 @AfterEach annotation becomes your best friend. In this comprehensive guide, we will dive deep into how to use this lifecycle callback to manage resource cleanup, maintain test integrity, and ensure that every test runs in a pristine environment. What is @AfterEach? The @AfterEach annotation marks a method that should be executed after every individual @Test method in the current class. Think of it as the "janitor" of your testing suite; no matter if your test passes, fails, or throws an unexpected exception, the @AfterEach method steps in to sweep the floor and reset the stage for the next performer. Unlike its counterpart @AfterAll (which runs once after the entire class is finished), @AfterEach is granular. It ensures that the state is reset immediately after each logic check, preventing "leakage" where the side effects of Test A interfere with the assertions of Test B.

Compact Strings in Java 9: How They Save Memory and Boost Performance

Starting with Java 9, the JVM quietly adopted a new internal representation for the java.lang.String class. The feature is called Compact Strings and, unless you went looking, you probably never noticed the change—yet it can shrink your application’s heap by 10-30% and speed up operations on text-heavy workloads. This post explains what compact strings are, how this subtle change delivers massive performance wins, and how you can measure the benefit on your own code. Get ready to reclaim your RAM! The Memory Drain Java 9 Tried to Solve Prior to JDK 9, every character inside a String was stored as a 16-bit char, using the UTF-16 encoding. The problem? For common languages like English, or text data formats like XML, JSON, log messages, and HTTP headers, most characters fall within the Latin-1 (ISO-8859-1) set, which perfectly fits into a single 8-bit byte. This meant that for a vast majority of applications, half of every character array was filled with redundant zeroes. That silent waste translated directly to: Larger Heap Footprint: Your application demands more RAM. More GC Pressure: The Garbage Collector has to work harder and longer. Lower CPU-Cache Locality: Data is scattered, slowing down processing. While developers could manually pack bytes, it came at the cost of code clarity and API compatibility. Clearly, a JVM-level fix was needed to make string handling efficient by default.

Java Stream API: How to Get the Last Element

Java Streams provide elegant ways to process collections, but retrieving the last element isn't as straightforward as calling a getLast() method. Since streams are designed for sequential processing without inherent indexing, developers need specific techniques to fetch the final element efficiently. This guide explores practical approaches to solve this common programming challenge. Whether you're processing large datasets or building concise functional pipelines, understanding these methods will help you write cleaner, more maintainable code. The Core Challenge Unlike List or Deque collections, Java Streams don't maintain bidirectional iteration or direct index access. Once elements pass through the pipeline, they're consumed. This design makes operations like stream().last() impossible without workarounds. However, several clever techniques leverage stream reduction and size information to achieve the desired result. Approach 1: Using reduce() Method The reduce() operation processes each element while retaining only the last one seen. This approach works beautifully for both sequential and parallel streams. import java.util.Optional; import java.util.stream.Stream; public class LastElementWithReduce { public static void main(String[] args) { Stream fruitStream = Stream.of("apple", "banana", "cherry", "date"); Optional lastElement = fruitStream.reduce((first, second) -> second); lastElement.ifPresent(element -> System.out.println("Last fruit: " + element) ); } }

Get Year, Month, Day from Date in Java

Extracting individual date components like year, month, and day is a common requirement in Java applications. Whether you're working with legacy Date objects or modern date-time APIs, this guide will show you multiple approaches to accomplish this task efficiently. 1. Using Calendar Class (Legacy Approach) Before Java 8, the Calendar class was the standard way to extract date fields from a Date object. While it's still supported, this approach is considered outdated and less intuitive than modern alternatives. import java.util.Calendar; import java.util.Date; public class DateExtractor { public static void main(String[] args) { Date currentDate = new Date(); Calendar calendar = Calendar.getInstance(); calendar.setTime(currentDate); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH) + 1; // Months are 0-based int day = calendar.get(Calendar.DAY_OF_MONTH); System.out.println("Year: " + year); System.out.println("Month: " + month); System.out.println("Day: " + day); } } Note: The Calendar.MONTH field returns values from 0 (January) to 11 (December), so you need to add 1 to get the standard 1-12 month numbering.

8086 Assembly Program to Generate the Fibonacci Sequence

This blog post will walk you through an 8086 assembly program designed to generate the Fibonacci sequence. While this may sound simple, it’s an excellent example for understanding looping, arithmetic operations, and register management in assembly language. The Fibonacci Series The Fibonacci series is a sequence where each number is the sum of the two preceding ones: 0, 1, 1, 2, 3, 5, 8, 13, 21, … In this program, we’ll generate the first 10 Fibonacci numbers and store them in memory. Code ; 8086 Program to Generate 10 Fibonacci Numbers data segment COUNT equ 10 ; Number of terms to generate FIB_SERIES db COUNT dup(?) ; Array to store the series data ends code segment assume cs:code, ds:data start: ; Initialize Data Segment (DS) register mov ax, data mov ds, ax ; Use SI as a pointer to the array mov si, offset FIB_SERIES ; Seed the first two Fibonacci numbers ; Fib(0) = 0 mov byte ptr [si], 00h ; Fib(1) = 1 inc si mov byte ptr [si], 01h ; Set up loop counter. We already have 2 numbers, ; so we need to generate (COUNT - 2) more. mov cx, COUNT sub cx, 2 L1: ; AL = Fib(n-1) (e.g., [si]) mov al, [si] ; BL = Fib(n-2) (e.g., [si-1]) mov bl, [si-1] ; AL = Fib(n-1) + Fib(n-2) add al, bl ; Move pointer to next position Fib(n) inc si ; Store the new term: [si] = AL mov [si], al ; Decrement CX, loop if CX is not zero loop L1 ; Halt execution for debugging int 3 code ends end start

Building Native Images of Spring Boot Applications with GraalVM: A Step-by-Step Guide

In the ever-evolving landscape of cloud-native development and serverless architectures, the demand for applications with lightning-fast startup times and minimal memory footprints is greater than ever. Java, traditionally known for its "write once, run anywhere" philosophy, has sometimes faced criticism regarding these very aspects. However, with the advent of GraalVM and Spring Boot's dedicated support, Java is now a formidable contender in this space. This post will guide you through the process of building GraalVM native images of your Spring Boot native applications (specifically Spring Boot 3.x), demonstrating how to unlock significant optimizations in startup time and memory consumption, perfect for serverless Java and general cloud native Java deployments. Why Native Images? The GraalVM Advantage Traditional Java applications run on the Java Virtual Machine (JVM). While the JVM offers incredible runtime optimizations through its Just-In-Time (JIT) compiler, there's an inherent overhead: the JVM itself needs to start, classes need to be loaded, and code needs to be JIT-compiled at runtime. GraalVM Native Image technology compiles your Java application ahead-of-time (AOT) into a standalone executable. This executable includes the application code, required libraries, and a minimal runtime environment (the Substrate VM) – all compiled into a single binary. The benefits are substantial: Blazing Fast Startup: Native images typically start in milliseconds, making them ideal for serverless functions, microservices, and environments where rapid scaling is crucial. Reduced Memory Footprint: By eliminating the JVM overhead and only including the necessary code paths, native images use significantly less memory. Smaller Deployment Size: The resulting binary is often much smaller than a traditional JAR file bundled with a JRE. Lower Resource Consumption: Less CPU and memory usage translates to lower operational costs in cloud environments. Spring Boot 3.x has embraced GraalVM native image compilation with first-class support, making the process more seamless than ever.

Java 8: Exact Arithmetic Operations in the Math Class

With the arrival of Java 8, the java.lang.Math utility class received a bundle of new methods that let you work with floating‑point numbers at a higher level of precision. Whether you’re implementing numerical libraries, doing financial calculations, or simply trying to understand IEEE 754 behaviour in Java, these additions are invaluable. Below we’ll walk through the most useful operators, illustrate their usage, and explain why they matter. 1. Inspecting the Exponent The Math.getExponent(double d) and Math.getExponent(float f) methods extract the unbiased exponent from a double or float. This is equivalent to stripping the mantissa and returning the raw exponent as an int. double d = 8.0; // 2³ int exp = Math.getExponent(d); System.out.println(exp); // prints 3 float f = 0.125f; // 2⁻³ System.out.println(Math.getExponent(f)); // prints -3 These methods are often used for normalizing numbers or maps where the scale is critical.

TypeScript’s Great Divide: Understanding undefined vs. null

In the world of JavaScript and TypeScript, few concepts create as much quiet confusion as undefined and null. Both seem to represent “nothing,” yet they are not the same. Misunderstanding the distinction can lead to subtle bugs and unexpected behavior. Let’s clear the air once and for all. Think of them as two different kinds of “emptiness.” One is accidental, the other is intentional. Mastering this difference is a key step toward writing cleaner, more predictable code. Meet undefined: The Sound of Silence undefined is a primitive value that TypeScript (and JavaScript) uses to signify that a variable has been declared but has not been assigned a value. It’s the default state of “not yet initialized.” It’s the system telling you, “I have a space for this, but nothing’s in it yet.”

Securing Spring MVC with SiteMinder Pre‑Authentication – A Step‑by‑Step Guide

Enterprise Java applications frequently live behind a corporate Single Sign-On (SSO) gateway such as Broadcom (formerly CA) SiteMinder. SiteMinder authenticates users at the reverse-proxy layer — before any request ever reaches your application server — and then injects the verified identity into a well-known HTTP request header (typically SM_USER). Your Spring Boot application simply trusts that header and builds a security context from it, with no login form and no password handling of its own. This pattern is called pre-authentication: the heavy lifting of credential verification is delegated to an external system, and your app only needs to map the already-authenticated identity to application-level roles. Spring Security has first-class support for this via RequestHeaderAuthenticationFilter and PreAuthenticatedAuthenticationProvider. This tutorial walks through a complete Spring Boot 3.x / Spring Security 6.x configuration, covering Maven dependencies, the security filter chain using the modern lambda DSL, a UserDetailsService implementation, and tips for testing locally without a real SiteMinder agent.