I use many SimpleDateFormat objects inside my servlet. Unfortunately, SimpleDateFormat is not thread safe. So I was thinking of a wrapper with ThreadLocal to facilitate the reuse of SimpleDateFormat objects. I wrote a 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(); } }
In fact, this apparently leads to a memory leak. When disconnecting my webapp, Tomcat logs the following error message:
SEVERE: the web application [] created a ThreadLocal with a 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 could not delete it, when the web application was stopped. This will likely lead to a memory leak.
I understand the reason for the memory leak, but what is the best way to handle SimpleDateFormat objects (or any other objects not containing threads) in Servlets?
source share