Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I declare Jackson's ObjectMapper as a static field?

Tags:

java

json

jackson

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(); } 
like image 272
Cheok Yan Cheng Avatar asked Oct 11 '10 16:10

Cheok Yan Cheng


People also ask

Is ObjectMapper Jackson thread-safe?

ObjectMapper is a completely thread-safe service class, it is meant to be used as singleton across the lifetime of the application. It is also very expensive to create.

Should you reuse ObjectMapper?

For e.g., you should reuse the ObjectMapper instance across JSON conversions throughout your code. The Jackson Javadocs state that those instances are thread-safe, and therefore it should be alright to do it.

Does Jackson use fields or getters?

Jackson uses the setter and getter methods to auto-detect the private field and updates the field during deserialization. Assume you have defined all the fields or properties in your Java class so that both input JSON and output Java class have identical fields.

What does Jackson ObjectMapper do?

The Jackson ObjectMapper can parse JSON from a string, stream or file, and create a Java object or object graph representing the parsed JSON. Parsing JSON into Java objects is also referred to as to deserialize Java objects from JSON. The Jackson ObjectMapper can also create JSON from Java objects.


1 Answers

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).

like image 100
StaxMan Avatar answered Oct 05 '22 16:10

StaxMan