Gson Converter with SimpleDateFormat -


i'm running code uses gson converter simple date format function , once in while date formatting messes either it's displaying date in 1969-1970 depending on time zone or takes , displays random date.

static class dateserializer implements jsondeserializer<date> {     @override     public date deserialize(jsonelement jsonelement, type typeof, jsondeserializationcontext context)             throws jsonparseexception {         (simpledateformat simpledateformat : date_formats) {             try {                 simpledateformat.setlenient(true);                  return simpledateformat.parse(jsonelement.getasstring());             } catch (parseexception e) {             }         }         return null;     } } static {     final timezone gmt_timezone = timezone.gettimezone("gmt");     int = 0;     (string format : date_format_strings) {         simpledateformat dateformat = new simpledateformat(format, locale.us);         dateformat.settimezone(gmt_timezone);         date_formats[i++] = dateformat;     } } gson gson = new gsonbuilder()             .registertypeadapter(date.class, new dateserializer())             .create(); private static final string[] date_format_strings = new string[]{"yyyy-mm-dd't'hh:mm:sszzzz",                                                                  "yyyy-mm-dd't'hh:mm:ss'z'"}; 

the problem simpledateformat not thread-safe. deserialization happening across multiple threads improve performance, due non-thread-safety of simpledateformat, garbage in parsed dates.

two options solving problem creating new simpledateformat each time need it, or enforcing atomicity doing such creating lock on date format.

for example, gson's defaultdatetypeadapter takes latter approach.


Comments