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(); }
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.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With