Fixed issue 162 by making default date adapter thread-safe by synchronizing serialize() and deserialize() methods.

This commit is contained in:
Inderjeet Singh 2009-09-25 17:14:48 +00:00
parent 8297437610
commit 19ae6c0763

View File

@ -54,8 +54,7 @@ import java.util.UUID;
*/ */
final class DefaultTypeAdapters { final class DefaultTypeAdapters {
private static final DefaultDateTypeAdapter DATE_TYPE_ADAPTER = private static final DefaultDateTypeAdapter DATE_TYPE_ADAPTER = new DefaultDateTypeAdapter();
new DefaultDateTypeAdapter(DateFormat.getDateTimeInstance());
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private static final EnumTypeAdapter ENUM_TYPE_ADAPTER = new EnumTypeAdapter(); private static final EnumTypeAdapter ENUM_TYPE_ADAPTER = new EnumTypeAdapter();
@ -234,28 +233,32 @@ final class DefaultTypeAdapters {
static class DefaultDateTypeAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> { static class DefaultDateTypeAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
private final DateFormat format; private final DateFormat format;
public DefaultDateTypeAdapter(String datePattern) { DefaultDateTypeAdapter() {
this.format = DateFormat.getDateTimeInstance();
}
DefaultDateTypeAdapter(final String datePattern) {
this.format = new SimpleDateFormat(datePattern); this.format = new SimpleDateFormat(datePattern);
} }
DefaultDateTypeAdapter(DateFormat format) { DefaultDateTypeAdapter(final int style) {
this.format = format;
}
public DefaultDateTypeAdapter(int style) {
this.format = DateFormat.getDateInstance(style); this.format = DateFormat.getDateInstance(style);
} }
public DefaultDateTypeAdapter(int dateStyle, int timeStyle) { public DefaultDateTypeAdapter(final int dateStyle, final int timeStyle) {
this.format = DateFormat.getDateTimeInstance(dateStyle, timeStyle); this.format = DateFormat.getDateTimeInstance(dateStyle, timeStyle);
} }
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { // These methods need to be synchronized since JDK DateFormat classes are not thread-safe
// See issue 162
public synchronized JsonElement serialize(
Date src, Type typeOfSrc, JsonSerializationContext context) {
String dateFormatAsString = format.format(src); String dateFormatAsString = format.format(src);
return new JsonPrimitive(dateFormatAsString); return new JsonPrimitive(dateFormatAsString);
} }
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) public synchronized Date deserialize(
JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException { throws JsonParseException {
if (!(json instanceof JsonPrimitive)) { if (!(json instanceof JsonPrimitive)) {
throw new JsonParseException("The date should be a string value"); throw new JsonParseException("The date should be a string value");