ThreadLocal的误用可能会导致OutOfMemoryError

本文探讨了如何正确使用ThreadLocal,以及如果不当使用可能导致的内存泄漏问题,特别是在线程池环境中。ThreadLocal误用可能导致PermGen空间溢出错误。建议在web应用中谨慎使用ThreadLocal,并确保在适当的时候调用remove()方法。
摘要由CSDN通过智能技术生成

推荐Java Code Geeks上的两篇文章:


When and how to use a ThreadLocal

http://www.javacodegeeks.com/2013/10/when-and-how-to-use-a-threadlocal.html
 

——误用ThreadLocal可能会导致OutOfMemoryError。

Instead of grinding my teeth, I decided to open up the topic by publishing two articles, first of which you are currently reading. In the post I explain the motivation behind ThreadLocal usage. In the second post currently in progress I will open up the ThreadLocal bonnet and look at the implementation.

【正例】为不同地区的用户显示不同的日期格式

Let us start with an imaginary scenario in which ThreadLocal usage is indeed reasonable. For this, say hello to our hypothetical developer, named Tim. Tim is developing a webapp, in which there is a lot of localized content. For example a user from California would expect to be greeted with date formatted using a familiar MM/dd/yy pattern, one from Estonia on the other hand would like to see a date formatted according to dd.MM.yyyy. So Tim starts writing code like this:

    public String formatCurrentDate() {
        DateFormat df = new SimpleDateFormat( "MM/dd/yy");
         return df.format( new Date());
    }
 
     public String formatFirstOfJanyary1970() {
        DateFormat df = new SimpleDateFormat( "MM/dd/yy");
         return df.format( new Date( 0));
    }

改进:将DateFormat提取出来作为实例变量。

After a while, Tim finds this to be boring and against good practices – the application code is polluted with such initializations. So he makes a seemingly reasonable move by extracting the DateFormat to an instance variable. After making the move, his code now looks like the following:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值