Course – Black Friday 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

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

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

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 – 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

Partner – Orkes – NPI EA (cat=Java)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

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 – Black Friday 2025 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

1. Introduction

Jackson’s ObjectMapper sits at the center of most Java JSON pipelines. Because building and configuring it touches the classpath, discovers modules, and warms several internal caches, many teams wonder: should we keep a single, shared mapper or spin up a new one per call?

In this tutorial, we review the trade‑offs and Jackson’s real thread‑safety guarantees, demonstrate a genuine race condition with JUnit 5, and finish with pragmatic guidance we can adopt today.

2. Why Developers Reach for a static ObjectMapper?

Creating an ObjectMapper does much more than allocate a POJO.

It loads and registers Modules, constructs Serializer/Deserializer caches, scans annotations, and wires up default formatters.

Doing that work on every request can become expensive. Therefore, it is common to see a helper like:

public final class JsonUtils {
    public static final ObjectMapper MAPPER = new ObjectMapper();
}

One line gives the whole JVM a warm, reusable mapper – great for latency, but only if we handle configuration correctly.

3. Thread‑Safety: What Jackson Guarantees

Before we delve into concurrency, let’s take a look at what Jackson guarantees:

  • Immutable after first use. The official Javadoc states that an ObjectMapper is fully thread‑safe, provided all configuration is completed before any read or write calls
  • Configuration methods copy, they don’t patch. Calls such as enable(), disable(), or configure() install a brand‑new immutable SerializationConfig/DeserializationConfig instance via a single volatile write. Existing writers keep the old snapshot, so concurrent toggles do not corrupt data
  • Mutable collaborators break the contract. If we inject a stateful, non‑thread‑safe object (e.g., java.text.SimpleDateFormat) through setDateFormat(), we re‑introduce unsafe shared state

The danger, therefore, lies in sharing mutable helpers that Jackson merely delegates to.

4. Performance Impact of Re‑Use

A singleton mapper delivers:

  • Zero cold‑start cost – module discovery and annotation scanning run only once
  • Hot serializer caches – expensive Serializers stay in memory
  • Less garbage – each request allocates only the incremental buffers it needs

Those wins disappear if the mapper is constantly reconfigured or cloned, so we should aim for “configure once, use forever.”

5. Drawbacks of a Global Mapper

Using a single, application‑wide ObjectMapper certainly avoids boilerplate, but it also opens the door to subtle bugs. All the issues below stem from the fact that every part of the codebase is talking to the same mutable instance.

5.1. Leaky Configuration

A configuration change made in one place leaks everywhere else because there is only one mapper:

@Test
void whenRegisteringDateFormatGlobally_thenAffectsAllConsumers() throws Exception {
    Map<String, Date> payload = singletonMap("today",
      Date.from(LocalDate.of(1998, 2, 9).atTime(12, 0).toInstant(ZoneOffset.UTC)));

    String before = GLOBAL_MAPPER.writeValueAsString(payload);
    assertEquals("{\"today\":887025600000}", before);

    GLOBAL_MAPPER.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));

    String after = GLOBAL_MAPPER.writeValueAsString(payload);
    assertEquals("{\"today\":\"1998-02-09\"}", after);
}

Although the production code that serializes LocalDate is untouched, its output flips as soon as another class registers the DateFormat.

5.2. Hidden Coupling in Tests

Unit tests that share the global mapper must either run in a fixed order or reset it manually – otherwise, they leave hidden state behind:

@Test
@Order(1)
void givenCustomDateFormat_whenConfiguredFirst_thenPasses() throws Exception {
    GLOBAL_MAPPER.setDateFormat(new SimpleDateFormat("dd-MM-yyyy"));
    Map<String, Date> payload = Collections.singletonMap("date",
      Date.from(LocalDate.of(1998, 2, 9).atTime(12, 0).toInstant(ZoneOffset.UTC)));
    String json = GLOBAL_MAPPER.writeValueAsString(payload);
    assertEquals("{\"date\":\"09-02-1998\"}", json);
}

@Test
@Order(2)
void givenDefaultDateFormat_whenRunAfterMutation_thenFails() throws Exception {
    Map<String, Date> payload = Collections.singletonMap("date", 
      Date.from(LocalDate.of(1998, 2, 9).atTime(12, 0).toInstant(ZoneOffset.UTC)));
    String json = GLOBAL_MAPPER.writeValueAsString(payload);
    assertNotEquals("{\"date\":887025600000}", json);
}

The second test succeeds only if it runs before the first one – an invisible dependency easily missed during refactoring or parallel execution.

5.3. Conflicting Requirements

Different consumers may need incompatible settings. With a global mapper, the last configuration wins. DateFormat is mutable, so switching it globally can break earlier expectations:

@Test
void whenSwitchingDateFormatGlobally_thenEndpointsCollide() throws Exception {
    SimpleDateFormat iso = new SimpleDateFormat("yyyy-MM-dd");
    GLOBAL_MAPPER.setDateFormat(iso);

    Map<String, Date> payload = Collections.singletonMap(
      "dob",
      Date.from(LocalDate.of(1990, 10, 5).atTime(12, 0).toInstant(ZoneOffset.UTC)));

    String forA = GLOBAL_MAPPER.writeValueAsString(payload);
    assertEquals("{\"dob\":\"1990-10-05\"}", forA);

    SimpleDateFormat european = new SimpleDateFormat("dd/MM/yyyy");
    GLOBAL_MAPPER.setDateFormat(european);

    String forB = GLOBAL_MAPPER.writeValueAsString(payload);
    assertEquals("{\"dob\":\"05/10/1990\"}", forB);

    String nowBrokenForA = GLOBAL_MAPPER.writeValueAsString(payload);
    assertNotEquals(forA, nowBrokenForA);
}

5.4. Race Conditions

Let’s create a scenario where it’s possible to have race conditions. We’ll use setDateFormat() for it, as it’s not thread safe:

@Test
void whenSimpleDateFormatChanges_thenConflictHappens() throws Exception {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    GLOBAL_MAPPER.setDateFormat(format);

    Callable<String> task = () -> GLOBAL_MAPPER.writeValueAsString(Map.of("key",
    Date.from(LocalDate.of(1998, 2, 9).atTime(12, 0).toInstant(ZoneOffset.UTC))));
    Callable<Void> mutator = () -> {
        format.applyPattern("dd-MM-yyyy");
        return null;
    };

    Future<String> taskResult1 = POOL.submit(task);
    assertEquals("{\"key\":\"1998-02-09\"}", taskResult1.get());
    POOL.submit(mutator).get();
    Future<String> taskResult2 = POOL.submit(task);
    assertEquals("{\"key\":\"09-02-1998\"}", taskResult2.get());
}

As we can see, mutating format will also cause a mutation in ObjectMapper, and the results will be different.

6. Scoped Alternatives

When we don’t want to create a global instance and also don’t want to create a new instance on every use of an ObjectMapper, we need to look for alternatives. Let’s see how we can scope ObjectMapper to find a middle ground.

6.1. Dependency Injection (Spring)

Spring beans are singletons by default, so you can expose exactly one mapper per ApplicationContext without resorting to static state:

@Configuration
public class JacksonConfig {
    @Bean
    @Primary
    public ObjectMapper objectMapper() {
        return JsonMapper.builder()
          .addModule(new JavaTimeModule())
          .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS)
          .build();
    }
}

6.2. Lightweight Copies for One‑Off Tweaks

If we need, for example, pretty‑printing for a single response, we can fork the mapper instead of mutating the global one:

ObjectMapper localCopy =
  globalMapper.copy().enable(SerializationFeature.INDENT_OUTPUT);

The clone reuses most internal resources but shields the parent mapper from further change. Let’s see it in action:

@Test
void whenUsingCopyScopedMapper_thenNoInterference() throws Exception {
    ObjectMapper localCopy = GLOBAL_MAPPER.copy().enable(SerializationFeature.INDENT_OUTPUT);
    assertEquals("{\n  \"key\" : \"value\"\n}", localCopy.writeValueAsString(Map.of("key", "value")));
    assertEquals("{\"key\":\"value\"}", GLOBAL_MAPPER.writeValueAsString(Map.of("key", "value")));
}

With this unit test, we can prove that the local copy indeed doesn’t mutate the global mapper.

7. Conclusion

In this article, we discussed a static ObjectMapper. It is perfectly safe if – and only if – we finish all configuration before the first call and avoid injecting mutable helpers. Where that discipline is hard or impossible, we should prefer a DI singleton or a cheap copy() call.

Most importantly, keep mutable, non‑thread‑safe objects like SimpleDateFormat out of global scope and let Jackson do what it was designed to do – deliver fast, predictable JSON processing across threads.

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.
Course – Black Friday 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

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

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

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 – Black Friday 2025 – NPI (All)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

eBook Jackson – NPI EA – 3 (cat = Jackson)
4 Comments
Oldest
Newest
Inline Feedbacks
View all comments