杰克逊对象映射器JsonGenerator-线程安全吗? [英] Jackson ObjectMapper & JsonGenerator - is it thread-safe?

查看:360
本文介绍了杰克逊对象映射器JsonGenerator-线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个项目,该项目使用杰克逊更快的xml通过自定义序列化器和反序列化器将POJO序列化/反序列化到Json.据我了解,一旦创建并配置了ObjectMapper,它就是线程安全的.但是,我注意到在使用JMeter运行测试时,偶尔会发生以下情况-

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 -

  • 线程1进入CustomerSerializer并开始序列化
  • 线程2进入CustomSerializer,并与线程1交互,并开始从头到尾进行序列化
  • 线程1恢复,并且最后一个序列化的内容丢失了

似乎是在第二个线程进入时重置了JsonGenerator实例-肯定不应该发生这种情况吗?我检查了几个站点和线程,以查看是否需要设置任何设置或功能,但是据我了解,ObjectMapper重用了JsonGenerator实例,这可能是问题吗?

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

以及使用位置的示例

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

推荐答案

Jackson的ObjectMapper在每个序列化请求上创建一个新的JsonGenerator.从这个意义上讲,可以保证它是线程安全的.我可以看到的唯一可能导致您看到的行为的情况是,您的CustomSerializer是否具有正在共享的某些实例字段并且正在执行某种内部同步.

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.

这篇关于杰克逊对象映射器JsonGenerator-线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆