Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How correctly and thread safe reuse Jackson ObjectReader?

Tags:

java

json

jackson

Jackson have ObjectReader and documentation says that you need to use it for thread safety. But I can't understand how to do it correctly

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;

import java.io.IOException;
import java.util.Map;

public class JsonParser {
    private ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    private ObjectReader OBJECT_READER = new ObjectMapper().readerFor(Map.class);

    public Map<String, String> parseJson1(String json) throws IOException {
        ObjectReader objectReader = OBJECT_MAPPER.readerFor(Map.class);
        return objectReader.readValue(json);
    }

    public Map<String, String> parseJson2(String json) throws IOException {
        return OBJECT_READER.readValue(json);
    }
}

I wrote two samples

  1. parseJson1() - creates ObjectReader from ObjectMapper on each parsing
  2. parseJson2() - reuses single instance on ObjectReader

Which of them is right?

like image 365
Nawa Avatar asked Feb 11 '16 09:02

Nawa


People also ask

Is Jackson Objectreader thread-safe?

you FULLY configure it before any use (reading, writing or conversions) its use IS fully thread-safe — you can share mapper instances across threads, use concurrently.

Can Jackson ObjectMapper be reused?

ObjectMapper class can be reused and we can initialize it once as Singleton object.

Is ObjectMapper thread-safe?

Mapper instances are fully thread-safe provided that ALL configuration of the instance occurs before ANY read or write calls.

Is Jsondeserializer thread-safe?

As such, a single instance of JsonDateTimeSerializer (per type), which will have been registered with the JsonDateTimeSerializer , will be reused for all serializations. It must therefore be thread safe if you plan to use the ObjectMapper across multiple threads.


Video Answer


1 Answers

Documentation said it's "fully thread-safe" it means you can use parseJson2 safely without worring about invoking this method in concurrent threads.

https://fasterxml.github.io/jackson-databind/javadoc/2.5/com/fasterxml/jackson/databind/ObjectReader.html

Uses "fluent" (or, kind of, builder) pattern so that instances are immutable (and thus fully thread-safe with no external synchronization); new instances are constructed for different configurations. Instances are initially constructed by ObjectMapper and can be reused, shared, cached; both because of thread-safety and because instances are relatively light-weight.

like image 115
vvg Avatar answered Oct 28 '22 05:10

vvg