Skip to main content

Java

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.

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.

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.

Why You Should Never Use == to Compare Floats and Doubles in Java

Picture this: you’ve written a piece of Java code that performs some calculations. The logic seems flawless. You have an if statement that checks if two double or float values are equal. But for some reason, the check keeps failing, even when you’re sure the numbers should be identical. What’s going on? Welcome to one of the most common pitfalls in programming: comparing floating-point numbers. If you’ve ever written code like if (myDouble == 0.3), you might be in for a surprise. Let’s dive into why this is a bad idea and how to do it correctly. The Hidden Problem with Floating-Point Numbers The root of the issue lies in how computers store fractional numbers. Both float and double types in Java use a binary representation format (specifically, the IEEE 754 standard). The problem is that just like the fraction 1/3 cannot be perfectly represented as a finite decimal (it’s 0.33333…), many decimal fractions cannot be perfectly represented in binary. For example, the number 0.1 in decimal is an infinitely repeating fraction in binary. Because the computer has to truncate this at some point, the value it stores is not exactly 0.1, but a very, very close approximation. When you perform arithmetic with these approximations, the tiny precision errors can add up, leading to unexpected results.

Demystifying Thread Safety in Java: A Practical Guide

Imagine you’re collaborating on a Google Doc. You write a sentence, and at the exact same moment, your colleague deletes the paragraph it’s in. The result? Chaos. A corrupted document, lost work, and confusion. This is precisely what can happen inside your Java application when multiple threads—independent paths of execution—try to access and modify the same data simultaneously. Welcome to the world of concurrency and the critical concept of thread safety. An object or a piece of code is considered “thread-safe” if it continues to function correctly, without causing data corruption or unexpected behavior, even when accessed by multiple threads at the same time. Getting this right is the difference between a robust, predictable application and one that suffers from mysterious, hard-to-reproduce bugs. The Villain of Our Story: The Race Condition The most common concurrency problem is the race condition. It occurs when multiple threads “race” to access and change a shared resource, and the final outcome depends on the unpredictable order in which they execute.

Understanding LinkedHashMap in Java

Let's dive into a fascinating corner of Java’s Collections Framework: the LinkedHashMap. You might already be familiar with HashMap for its speedy key-value pair storage and LinkedHashSet for maintaining insertion order in a set. Well, LinkedHashMap is the best of both worlds, offering the familiar map interface with the added benefit of predictable iteration order. Let’s break down what makes LinkedHashMap so special and when you should consider using it. What is LinkedHashMap? In simple terms, LinkedHashMap is a hash table and a linked list implementation of the Map interface. It inherits all the goodness from HashMap (fast lookups, insertions, and deletions) but adds an internal doubly-linked list that runs through all of its entries. This linked list defines the iteration order, which can either be: Insertion Order: The default behavior, where elements are iterated in the order they were first inserted into the map. Access Order: Elements are iterated in the order they were last accessed (read or written). This is particularly useful for implementing LRU (Least Recently Used) caches. Like HashMap, LinkedHashMap allows one null key and multiple null values. Interface Hierarchy LinkedHashMap implements the following interfaces and extends the following class: java.io.Serializable java.util.Map java.lang.Cloneable And it extends java.util.HashMap.

Using Regular Expressions with Java 8 Predicates for Clean Code

Java 8 introduced some powerful functional interfaces, and one of the most versatile is Predicate. A Predicate represents a boolean-valued function of one argument. While it’s commonly used for simple checks, combining it with regular expressions opens up a world of possibilities for more complex data validation and filtering, all within a concise and readable lambda expression. In this post, we’ll explore how to leverage Java’s Pattern.compile() method to create efficient and reusable regex-based predicates. This approach is particularly useful when you need to perform the same regex validation multiple times, avoiding recompilation overhead for each check. The Problem with Repeated Regex Matching Let’s say you have a list of strings, and you want to filter them based on whether they match a specific regular expression. A naive approach might look something like this: