Pergunta

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?

Foi útil?

Solução

Aside from using an alternative implementation (commons-lang or joda) just create a new instance of SimpleDateFormat each time you what to use it.

I realise that this will make you feel dirty and in need of a bath, but it is very simple and doesn't require any effort on your part. The downside is that you will turn over a little bit more memory than before but in most normal web applications you are unlikely to notice against the noise of JDBC.

See my answer to ThreadLocal Resource Leak and WeakReference

Outras dicas

Create local objects or use FastDateFormat (FastDateFormat is a fast and thread-safe version of SimpleDateFormat.) from commons-lang. And joda-time is a common answer to all the date related questions ;-)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top