Jackson's JsonSerializer and thread safety Jackson's JsonSerializer and thread safety json json

Jackson's JsonSerializer and thread safety


If JsonDateTimeSerializer.serialize might be called from multiple threads, then this use of SimpleDateFormat is not safe. The common approach to avoid inefficient synchronization on SimpleDateFormat is explained well in this other answer. Adapting to your use case:

public class JsonDateTimeSerializer extends JsonSerializer<Date> {    private static final ThreadLocal<SimpleDateFormat> formatter = new ThreadLocal<SimpleDateFormat>() {        @Override        protected SimpleDateFormat initialValue() {            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        }    };    @Override    public void serialize(Date value, JsonGenerator gen, SerializerProvider sp) throws IOException {        gen.writeString(formatter.get().format(value));    }}


When Jackson sees your type for the first time, (depending on the type) it will build a BeanSerializer with the appropriate JsonSerializers for each property. This BeanSerializer is cached and reused for future serializations of the same Type.

As such, a single instance of JsonDateTimeSerializer (per type), which will have been registered with the JsonDateTimeSerializer, will be reused for all serializations. It must therefore be thread safe if you plan to use the ObjectMapper across multiple threads. (You should since the ObjectMapper itself is thread safe.)