Servlet 中的 SimpleDateFormat
我在 Servlet 中使用了很多 SimpleDateFormat 对象。不幸的是,SimpleDateFormat 不是线程安全的。因此,我考虑用 ThreadLocal 包装它以促进 SimpleDateFormat 对象的重用。我编写了一个实用程序类来实现此功能:
public class DateUtil {
private final static ThreadLocal<SimpleDateFormat> dateFormat = new ThreadLocal<SimpleDateFormat>() {
return new SimpleDateFormat();
}
public static SimpleDateFormat get () {
return dateFormat.get();
}
}
实际上,这似乎会导致内存泄漏。关闭我的 web 应用程序时,Tomcat 记录以下错误消息:
严重:Web 应用程序 [] 创建了一个 ThreadLocal,其键类型为 [null](值 [com.example.util.DateUtil$2@50242f7d]),值类型为 [java.text.SimpleDateFormat](值 [ java.text.SimpleDateFormat@d91b489b]),但在 Web 应用程序停止时未能将其删除。这很可能会造成内存泄漏。
我了解内存泄漏的原因,但是在 Servlet 中处理 SimpleDateFormat 对象(或任何其他非线程安全对象)的最佳方法是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
除了使用替代实现(commons-lang 或 joda)只需创建一个
SimpleDateFormat
的新实例每次你用什么就用什么。我知道这会让您感觉很脏并且需要洗澡,但这非常简单,不需要您付出任何努力。缺点是您将比以前多使用一点内存,但在大多数普通 Web 应用程序中您不太可能注意到 JDBC 的噪音。
请参阅我对 ThreadLocal 资源泄漏和 WeakReference 的回答
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
创建本地对象或使用 FastDateFormat(FastDateFormat 是 SimpleDateFormat 的快速且线程安全的版本。)来自 commons-lang。 joda-time 是所有与日期相关的问题的常见答案;-)
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 ;-)