File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
1
+ ## 该什么时候使用 ThreadLocal变量,它是如何工作的?
2
+ ### 回答1
3
+ 一种可能的(也是常见的)使用情形是你不想通过同步方式(synchronized)访问非线程安全的对象(说的就是SimpleDateFormat),而是想给每个线程一个对象实例的时候。
4
+ 例如
5
+ ```` java
6
+ public class Foo
7
+ {
8
+ // SimpleDateFormat is not thread-safe, so give one to each thread
9
+ private static final ThreadLocal<SimpleDateFormat > formatter = new ThreadLocal<SimpleDateFormat > (){
10
+ @Override
11
+ protected SimpleDateFormat initialValue ()
12
+ {
13
+ return new SimpleDateFormat (" yyyyMMdd HHmm" );
14
+ }
15
+ };
16
+
17
+ public String formatIt (Date date )
18
+ {
19
+ return formatter. get(). format(date);
20
+ }
21
+ }
22
+ ````
23
+ ### 回答2
24
+ 因为ThreadLocal是一个既定线程内部的数据引用,你可能在使用线程池的应用服务器上因此引起类加载时候的内存泄漏。你需要使用remove()方法很小心地清理TheadLocal中get()或者set()的变量。
25
+ 如果程序执行完毕没有清理的话,它持有的任何对类的引用将作为部署的Web应用程序的一部分仍保持在永久堆,永远无法得到回收。重新部署/取消部署也无法清理对应用程序类的引用,因为线程不是被你的应用程序所拥有的。
26
+ 每次成功部署都会创建一个永远不会被垃圾回收类的实例。
27
+
28
+ 最后将会遇到内存不足的异常-java.lang.java.lang.OutOfMemoryError: PermGen space -XX: MaxPermSize ,在google了很多答案之后你可能只是增加了-XX: MaxPermSize ,而不是修复这个bug。
29
+ 倘若你的确遇到这种问题,可以通过[ Eclipse's Memory Analyzer] ( http://www.eclipse.org/mat/ ) 或根据[ Frank Kieviet's guide] ( https://blogs.oracle.com/fkieviet/entry/classloader_leaks_the_dreaded_java ) 和 [ followup] ( https://blogs.oracle.com/fkieviet/entry/how_to_fix_the_dreaded ) 来判断哪些线程和类保留了那些引用。
30
+
31
+ 更新:又发现了[ Alex Vasseur's blog entry] ( http://avasseur.blogspot.jp/2003/11/threadlocal-and-memory-leaks.html ) ,它帮助我查清楚了一些ThreadLocal的问题。
32
+
33
+ stackoverflow链接:http://stackoverflow.com/questions/817856/when-and-how-should-i-use-a-threadlocal-variable
You can’t perform that action at this time.
0 commit comments