Skip to content

Commit 9879e9a

Browse files
committed
Fix multi-threaded access to static DateFormatter
1 parent f93c6b7 commit 9879e9a

File tree

1 file changed

+6
-5
lines changed

1 file changed

+6
-5
lines changed

src/main/java/org/bbottema/javareflection/valueconverter/converters/StringConverters.java

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -237,18 +237,19 @@ public UUID apply(String value) {
237237

238238
static class StringToDateFunction implements Function<String, Date> {
239239

240-
// Quoted "Z" to indicate UTC, no timezone offset
241-
private static final DateFormat DATETIME_FORMAT_SIMPLE = new SimpleDateFormat("yyyy-MM-dd");
242-
private static final DateFormat DATETIME_FORMAT_ISO8601 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
240+
private static ThreadLocal<DateFormat> DATETIME_FORMAT_SIMPLE =
241+
new ThreadLocal<DateFormat>() { public DateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd"); } };
242+
private static ThreadLocal<DateFormat> DATETIME_FORMAT_ISO8601 =
243+
new ThreadLocal<DateFormat>() { public DateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd HH:mm"); } };
243244
private IllegalArgumentException INCOMPATIBLE_EXCEPTION = new IllegalArgumentException("not compatible with yyyy-MM-dd or yyyy-MM-dd HH:mm");
244245

245246
@Override
246247
public Date apply(String value) {
247248
try {
248-
return DATETIME_FORMAT_ISO8601.parse(value);
249+
return DATETIME_FORMAT_ISO8601.get().parse(value);
249250
} catch (IllegalArgumentException | ParseException e1) {
250251
try {
251-
return DATETIME_FORMAT_SIMPLE.parse(value);
252+
return DATETIME_FORMAT_SIMPLE.get().parse(value);
252253
} catch (IllegalArgumentException | ParseException e2) {
253254
throw new IncompatibleTypeException(value, String.class, Date.class, INCOMPATIBLE_EXCEPTION);
254255
}

0 commit comments

Comments
 (0)