Skip to main content

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.

Leveraging Virtual Threads in Spring Boot 3.4+: Building High-Throughput Services

I've been shipping Java services for over a decade. I've tuned Tomcat thread pools, profiled connection leaks, and once reluctantly rewrote a critical service in WebFlux because blocking threads were killing us at scale. So when Java 21 landed with virtual threads baked in, I didn't just read the JEP — I immediately threw it at a production-like load test. The results were not subtle. This post is what I wish existed back then: an honest, methodical walkthrough of enabling virtual threads in Spring Boot 3.4, with real benchmark methodology, the gotchas that will actually bite you in production, and a clear-eyed take on when virtual threads won't help at all.

Spring Boot RestTemplate with Basic Auth: A Modern Guide

Communicating between microservices is a fundamental aspect of modern application development. Often, these services need to be secured. One of the simplest and most widely supported methods for securing REST APIs is Basic Authentication. In this guide, we’ll walk through how to configure and use Spring Boot’s RestTemplate to consume a REST API protected with Basic Auth. We’ll cover the modern, recommended approach using Spring Security’s component-based configuration, updating older patterns you might find in other tutorials. Project Setup First, ensure your Spring Boot project includes the spring-boot-starter-web dependency. This starter conveniently bundles everything we need, including Spring MVC for creating the REST service, Tomcat as the embedded server, and RestTemplate support. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> You’ll also need the spring-boot-starter-security dependency to enable security features. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>