I'm using a lot of SimpleDateFormat-objects within my Servlet. Unfortunately, SimpleDateFormat is not thread-safe. Thus, I thought about wrapping it wih ThreadLocal to foster the reuse of SimpleDateFormat-objects. I wrote an util-class to enable this:
public class DateUtil {
private final static ThreadLocal<SimpleDateFormat> dateFormat = new ThreadLocal<SimpleDateFormat>() {
return new SimpleDateFormat();
}
public static SimpleDateFormat get () {
return dateFormat.get();
}
}
Actually, this seems to lead to a memory-leak. When shutting down my webapp, Tomcat logs the following error message:
SEVERE: The web application [] created a ThreadLocal with key of type [null] (value [com.example.util.DateUtil$2@50242f7d]) and a value of type [java.text.SimpleDateFormat] (value [java.text.SimpleDateFormat@d91b489b]) but failed to remove it when the web application was stopped. This is very likely to create a memory leak.
I understand the reason for the memory-leak, but what is the best way to handle SimpleDateFormat-objects (or any other non-thread-safe objects) within Servlets?