eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

Generally speaking, the Java documents strongly discourage us from serializing a lambda expression. That’s because the lambda expression will generate synthetic constructs. And, these synthetic constructs suffer several potential problems: no corresponding construct in the source code, variation among different Java compiler implementations, and compatibility issues with a different JRE implementation. However, sometimes, serializing a lambda is necessary.

In this tutorial, we’re going to explain how to serialize a lambda expression and its underlying mechanism.

2. Lambda and Serialization

When we use Java Serialization to serialize or deserialize an object, its class and non-static fields must be all serializable. Otherwise, it will lead to NotSerializableException. Likewise, when serializing a lambda expression, we must make sure its target type and capturing arguments are serializable.

2.1. A Failed Lambda Serialization

In the source file, let’s use the Runnable interface to construct a lambda expression:

public class NotSerializableLambdaExpression {
    public static Object getLambdaExpressionObject() {
        Runnable r = () -> System.out.println("please serialize this message");
        return r;
    }
}

When trying to serialize the Runnable object, we’ll get a NotSerializableException. Before going on, let’s explain it a little bit.

When the JVM encounters a lambda expression, it will use the built-in ASM to build an inner class. So, what does this inner class look like? We can dump this generated inner class by specifying the jdk.internal.lambda.dumpProxyClasses property on the command line:

-Djdk.internal.lambda.dumpProxyClasses=<dump directory>

Be careful here: When we replace the <dump directory> with our target directory, this target directory had better be empty because the JVM may dump quite a few unexpected generated inner classes if our project depends on third-party libraries.

After dumping, we can inspect this generated inner class with an appropriate Java decompiler:

not serializable lambda expression generated inner class

In the above picture, the generated inner class only implements the Runnable interface, which is the lambda expression’s target type. Also, in the run method, the code will invoke the NotSerializableLambdaExpression.lambda$getLambdaExpressionObject$0 method, which is generated by the Java compiler and represents our lambda expression implementation.

Because this generated inner class is our lambda expression’s actual class and it doesn’t implement the Serializable interface, the lambda expression isn’t suitable for serialization.

2.2. How to Serialize Lambda

At this point, the problem falls to the point: how to add the Serializable interface to the generated inner class? The answer is casting a lambda expression with an intersection type that combines the functional interface and the Serializable interface.

For example, let’s combine the Runnable and Serializable into an intersection type:

Runnable r = (Runnable & Serializable) () -> System.out.println("please serialize this message");

Now, if we try to serialize the above Runnable object, it will succeed.

However, if we do this often, it can introduce a lot of boilerplate. To make the code clean, we can define a new interface that implements both Runnable and Serializable:

interface SerializableRunnable extends Runnable, Serializable {
}

Then we can use it:

SerializableRunnable obj = () -> System.out.println("please serialize this message");

But we should also be careful not to capture any non-serializable arguments. For example, let’s define another interface:

interface SerializableConsumer<T> extends Consumer<T>, Serializable {
}

Then we may select the System.out::println as its implementation:

SerializableConsumer<String> obj = System.out::println;

As a result, it will lead to a NotSerializableException. That’s because this implementation will capture as its argument the System.out variable, whose class is PrintStream, which is not serializable.

3. The Underlying Mechanism

At this point, we may be wondering: What happens underneath after we introduce an intersection type?

To have a basis for discussion, let’s prepare another piece of code:

public class SerializableLambdaExpression {
    public static Object getLambdaExpressionObject() {
        Runnable r = (Runnable & Serializable) () -> System.out.println("please serialize this message");
        return r;
    }
}

3.1. The Compiled Class File

After compiling, we can use the javap to inspect the compiled class:

javap -v -p SerializableLambdaExpression.class

The -v option will print verbose messages, and the -p option will display private methods.

And, we may find that the Java compiler provides a $deserializeLambda$ method, which accepts a SerializedLambda parameter:

deserialize lambda method bytecode

For readability, let’s decompile the above bytecode into Java code:

deserialize lambda method java code

The main responsibility of the above $deserializeLambda$ method is to construct an object. First, it checks the SerializedLambda‘s getXXX methods with different parts of the lambda expression details. Then, if all conditions are met, it will invoke the SerializableLambdaExpression::lambda$getLambdaExpressionObject$36ab28bd$1 method reference to create an instance. Otherwise, it will throw an IllegalArgumentException.

3.2. The Generated Inner Class

Besides inspecting the compiled class file, we also need to inspect the newly generated inner class. So, let’s use the jdk.internal.lambda.dumpProxyClasses property to dump the generated inner class:

serializable lambda expression generated inner class

In the above code, the newly generated inner class implements both the Runnable and Serializable interfaces, which means it’s suitable for serialization. And, it also provides an extra writeReplace method. To look inside, this method returns a SerializedLambda instance describing the lambda expression implementation details.

To form a closed loop, there is one more thing missing: the serialized lambda file.

3.3. The Serialized Lambda File

As the serialized lambda file is stored in binary format, we can use a hex tool to check its contents:

serialized lambda file hex format

In the serialized stream, the hex “AC ED” (“rO0” in Base64) is the stream magic number, and the hex “00 05” is the stream version. But, the remaining data isn’t human-readable.

According to the Object Serialization Stream Protocol, the remaining data can be interpreted:

serialized lambda file parsed format

From the above picture, we may notice the serialized lambda file actually contains the SerializedLambda class data. To be specific, it contains 10 fields and corresponding values. And, these fields and values of the SerializedLambda class are bridges between the $deserializeLambda$ method in the compiled class file and the writeReplace method in the generated inner class.

3.4. Putting It All Together

Now, it’s time to combine different parts together:

how lambda serialization and deserialization works

When we use the ObjectOutputStream to serialize a lambda expression, the ObjectOutputStream will find the generated inner class contains a writeReplace method that returns a SerializedLambda instance. Then, the ObjectOutputStream will serialize this SerializedLambda instance instead of the original object.

Next, when we use the ObjectInputStream to deserialize the serialized lambda file, a SerializedLambda instance is created. Then, the ObjectInputStream will use this instance to invoke the readResolve defined in the SerializedLambda class. And, the readResolve method will invoke the $deserializeLambda$ method defined in the capturing class. Finally, we get the deserialized lambda expression.

To summarize, the SerializedLambda class is the key to the lambda serialization process.

4. Conclusion

In this article, we first looked at a failed lambda serialization example and explained why it failed. Then, we introduced how to make a lambda expression serializable. Finally, we explored the underlying mechanism of lambda serialization.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – LS – NPI (cat=Java)
announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)