Jackson Best Practices: Thread Safety
Jackson follows thread-safety rules typical for modern factory-based Java data format handlers (similar to what, say, Stax or JAXP implementations do). For example:
Factories (ObjectMapper, JsonFactory) are thread-safe once configured: so ensure that all configuration is done from a single thread, and before instantiating anything with factory.
Reader/writer instances (like JsonParser and JsonParser) are not thread-safe -- there is usually no need for them to be, but if for some reason you need to access them from multiple threads, external synchronization is needed
All transformer objects (custom serializers, deserializers) are expected to be stateless, and thereby thread safe -- state has to be stored somewhere outside instances (in ThreadLocal or context objects passed in, like DeserializationContext).
So... ?
Basically, following usage pattern is perfectly fine, regarding thread-safety:
class MyJsonProcessingClass
{
protected final static ObjectMapper defaultMapper = new ObjectMapper();
static { // if you need to change default configuration:
defaultMapper.configure(SerializationConfig.Feature.USE_STATIC_TYPING, true); // faster this way, not default
}
public String doJson(MyData dataObject) throws IOException
{
return defaultMapper.writeValueAsString(dataObject);
}
}Back to JacksonDocumentation
