Niranjan
Niranjan

Reputation: 2931

Jackson ObjectMapper - does changing configurations on ObjectReader impact usage of ObjectMapper by multiple threads

We have a Spring based application and we have defined a singleton bean for Jackson ObjectMapper class.

@Bean(name = "jacksonObjectMapper")
public ObjectMapper createObjectMapper() {
  return new ObjectMapper();
}

We have a use case to write a generic JSON Serializer/Deserializer which we wrote in following way:

public <T, U> T deserialize(final String inputJsonString, final Class<T> targetType, final Class<U> targetParameterType) throws JsonProcessingException, IOException {
  return objectMapper
    .reader(objectMapper.getTypeFactory().constructParametricType(targetType, targetParameterType))
    .without(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
    .readValue(inputJsonString);
}

Here I am using ObjectReader instead of ObjectMapper itself and changing some configurations on ObjectReader (e.g. .without(...)). My question is, will such configuration changes impact other threads which may be using the same ObjectMapper instance to do something else (may be simply deserializing or serializing)?

Could someone help me understand the details and guide me?

My apologies if I haven't explained the question clearly; please let me know and I can provide further details.

Upvotes: 1

Views: 1194

Answers (1)

wassgren
wassgren

Reputation: 19231

Short answer: No, ObjectReader configuration does not change the underlying ObjectMapper configuration.

Explanation: If you use the ObjectMapper directly and alter the configuration of the mapper it can lead to problems if the mapper is shared between multiple threads. However, if you do not change the underlying config you should be safe anyway (more reading here).

In your case you are calling the mapper.reader(...) method where you actually create an ObjectReader. The ObjectReader and ObjectWriter are immutable and therefore they never change the underlying state. Furthermore, even if you change the config of the underlying ObjectMapper the reader will not be affected.

Note that for each call to the mapper.reader(...) method you are creating a new ObjectReader so if you change your ObjectMapper config between calls to the reader method you may run into problems.

So, to summarize: If you create an ObjectReader and use the same reader in your thread you are safe.

Upvotes: 2

Related Questions