Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson's JsonSerializer and thread safety

I have a simple JsonSerializer in my Spring project:

public class JsonDateTimeSerializer extends JsonSerializer<Date> {
    private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void serialize(Date value, JsonGenerator gen, SerializerProvider sp) throws IOException {
        gen.writeString(DATE_FORMAT.format(value));
    }
}

And use it like:

@JsonSerialize(using = JsonDateTimeSerializer.class)
public Date getDate() {
    return date;
}

Do I have to take care of thread-safety and make the DATE_FORMAT synchronized (as SimpleDateFormat is not thread-safe)? I am not sure how exactly @JsonSerialize works - does it create just single serialized instance across all threads? Or does it create separate instance for each transformation?

like image 598
Laimoncijus Avatar asked Mar 20 '26 23:03

Laimoncijus


1 Answers

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));
    }
}
like image 167
janos Avatar answered Mar 22 '26 12:03

janos