Jackson ObjectMapper & JsonGenerator - is it thread-safe?

KingTravisG picture KingTravisG · Jan 6, 2014 · Viewed 7.5k times · Source

I currently have a project which uses jackson faster xml to serialize/deserialize POJOs to Json using custom serializers and deserializers. From what I understand, the ObjectMapper is thread-safe once it has been created and configured. However, I have noticed when running tests with JMeter that occasionally the following can happen -

  • Thread 1 enters CustomerSerializer and starts to serialize
  • Thread 2 enters CustomSerializer, interuptting Thread 1, and starts to serialize from start to finish
  • Thread 1 resumes, and the last thing being serialized is missing

It seems to be that the JsonGenerator instance is being reset when the second thread has entered - surely this shouldn't be happening? I have checked several sites and threads to see if there are any settings or features I need to set, but from what I understand the ObjectMapper reuses JsonGenerator instances, could this be the issue?

The following is a snippet from my custom serializer...

@Override
public final void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {

    jsonGenerator.writeStartObject();

    ... Code here ....

    jsonGenerator.writeEndObject();

    closeJsonGenerator(jsonGenerator);
}

And an example of where it is used

SimpleModule sm = new SimpleModule();
sm.addSerializer(new myCustomSerializer());
new ObjectMapper().registerModule(sm)
                  .writeValue(new myObject());

Answer

Sotirios Delimanolis picture Sotirios Delimanolis · Jan 6, 2014

Jackson's ObjectMapper creates a new JsonGenerator on each request for serialization. In that sense, it is guaranteed to be thread safe. The only thing that I can see that might cause the behavior you are seeing is if your CustomSerializer has some instance fields that it is sharing and is doing some kind of internal synchronization.