Jackson ObjectMapper & JsonGenerator - is it thread-safe?

六月ゝ 毕业季﹏ 提交于 2019-12-02 01:18:25

问题


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());

回答1:


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.



来源:https://stackoverflow.com/questions/20956385/jackson-objectmapper-jsongenerator-is-it-thread-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!