Json Series Analyzer and Thread Safety

I have a simple simple Json serializer 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; } 

Should I take care of thread safety and make DATE_FORMAT synchronization (since SimpleDateFormat not thread safe)? I'm not sure how @JsonSerialize works - does it only create one serialized instance for all threads? Or does he create a separate instance for each conversion?

+2
java json spring multithreading serialization
Sep 05 '14 at 7:32
source share
2 answers

When Jackson sees your type for the first time (depending on type), he will build a BeanSerializer with the corresponding JsonSerializer for each property. This BeanSerializer cached and reused for future serialization of the same Type .

Thus, for all serialization, one instance of JsonDateTimeSerializer (for each type) will be used, which will be registered using JsonDateTimeSerializer . Therefore, it should be thread safe if you plan to use ObjectMapper for multiple threads. (You should, since ObjectMapper itself is thread safe.)

0
Sep 06 '14 at 2:37
source share

If JsonDateTimeSerializer.serialize can be called from multiple threads, this use of SimpleDateFormat unsafe. The general approach to preventing inefficient synchronization on SimpleDateFormat well explained 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)); } } 
+3
Sep 05 '14 at 7:56
source share



All Articles