Pavel Vyazankin
Pavel Vyazankin

Reputation: 1580

Date parsing magic

Here is my code:

private static final DateFormat DATE_FORMAT = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
....
private static Date parseIfModifiedSince(HttpServletRequest request) {
    String lastModifiedHeader = "";
    try {
        lastModifiedHeader = request.getHeader(IF_MODIFIED_SINCE);
        return !StringUtils.isEmpty(lastModifiedHeader) ? DATE_FORMAT.parse(lastModifiedHeader) : null;
    } catch (Exception ex) {
        log.warn("Error while parsing If-Modified-Since date: \"" + lastModifiedHeader+"\"", ex);
        return null;
    }
}

Sometimes I see an exception:

WARN ru.planeta.web.res.ResourcesController 2013-03-29 20:16:58,635: Error while parsing If-Modified-Since date: "Fri, 29 Mar 2013 16:16:28 GMT"
java.lang.NumberFormatException: multiple points

I can't find any problem in code. What's wrong with me?

Upvotes: 0

Views: 245

Answers (2)

Aurand
Aurand

Reputation: 5537

As @Sarath mentioned, SimpleDateFormat is not thread safe. An alternate solution would be to use FastDateFormat, which is thread safe.

Upvotes: 0

1218985
1218985

Reputation: 8022

Declaring the SimpleDateFormat as a class-level variable exposes you to that problem since it isn't thread-safe. I would recommend you to create a new SimpleDateFormat object each time you need one and only assign it to a local variable within the method.

Upvotes: 1

Related Questions