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?
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));
}
}
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