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
parseJson1()
- creates ObjectReader from ObjectMapper on each parsingparseJson2()
- reuses single instance on ObjectReaderWhich of them is right?
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.
ObjectMapper class can be reused and we can initialize it once as Singleton object.
Mapper instances are fully thread-safe provided that ALL configuration of the instance occurs before ANY read or write calls.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With