SimpleDateFormat in servlets

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?

+2
source share
2 answers

Besides using an alternative implementation ( commons-lang or joda ) just create a new instance of SimpleDateFormat every time you use it.

I understand that this will make you feel dirty and in need of a bath, but it is very simple and does not require any effort on your part. The downside is that you will flip a bit more memory than before, but in most regular web applications you are unlikely to notice JDBC noise.

See my answer on ThreadLocal Leak and WeakReference

+5
source

Create local objects or use FastDateFormat (FastDateFormat is a fast and thread-safe version of SimpleDateFormat.) From commons-lang. And iodine-time is a general answer to all questions related to the date :-)

+3
source

Source: https://habr.com/ru/post/1502530/


All Articles