我应该将Jackson的ObjectMapper声明为静态字段吗? [英] Should I declare Jackson's ObjectMapper as a static field?

查看:2154
本文介绍了我应该将Jackson的ObjectMapper声明为静态字段吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

杰克逊图书馆的 ObjectMapper 班级似乎是线程安全的



这是否意味着我应该将我的 ObjectMapper 声明为像这样的静态字段

  class Me {
private static final ObjectMapper mapper = new ObjectMapper();
}

而不是像这样的实例级字段?

  class Me {
private final ObjectMapper mapper = new ObjectMapper();
}


解决方案

是的,这是安全的,推荐。



您引用的页面中唯一的警告是,一旦共享,您就无法修改映射器的配置;但你没有改变配置,所以没关系。如果您确实需要更改配置,您可以从静态块中执行此操作,也可以。但



编辑 :( 2013使用 ObjectWriter ObjectReader 对象,可以由 ObjectMapper 构造。
它们是完全不可变的,线程安全的,这意味着理论上甚至不可能导致线程安全问题(如果代码尝试使用 ObjectMapper 重新配置实例)。


The Jackson library's ObjectMapper class seems to be thread safe.

Does this mean that I should declare my ObjectMapper as a static field like this

class Me {
    private static final ObjectMapper mapper = new ObjectMapper();
}

instead of as an instance-level field like this?

class Me {
    private final ObjectMapper mapper = new ObjectMapper();
}

解决方案

Yes, that is safe and recommended.

The only caveat from the page you referred is that you can't be modifying configuration of the mapper once it is shared; but you are not changing configuration so that is fine. If you did need to change configuration, you would do that from the static block and it would be fine as well.

EDIT: (2013/10)

With 2.0 and above, above can be augmented by noting that there is an even better way: use ObjectWriter and ObjectReader objects, which can be constructed by ObjectMapper. They are fully immutable, thread-safe, meaning that it is not even theoretically possible to cause thread-safety issues (which can occur with ObjectMapper if code tries to re-configure instance).

这篇关于我应该将Jackson的ObjectMapper声明为静态字段吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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