無法解決共享對象的更新問題。(引用於《阿里巴巴JAVA開發規範》)
個人理解:
- 首先加不加 private 個人覺得是一種編程規範吧 類中的變量需要用private 來修飾。
- 我們知道對於static 修飾的變量在類的裝載時候纔會被加載,卸載時候纔會被釋放。如果大量使用不帶static 的對象會造成內存的浪費哦。
- 看一下ThreadLocal 源碼發現 ThreadLocal 實現方式實際上是通過一個靜態的map 去保存的。 引用的方式是弱引用 如果我們創建的大量的ThreadLocal 對象, 當虛擬機回收這些對象的時候 也就是key 被回收了 但是 value 還有弱引用指向 這個靜態的map 容易造成內存泄漏。 建議如果某個對象 不用了 可以自己remove 調。
static class ThreadLocalMap {
/**
* The entries in this hash map extend WeakReference, using
* its main ref field as the key (which is always a
* ThreadLocal object). Note that null keys (i.e. entry.get()
* == null) mean that the key is no longer referenced, so the
* entry can be expunged from table. Such entries are referred to
* as "stale entries" in the code that follows.
*/
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
- ThreadLocal 在設計上就是當前這個線程 本地的 共享的。 看了一下源碼ThreadLocal 的實現方式 是 每個Thread 裏面 維護一個自己的 ThreadLocalMap
在這個線程初始化的時候 會去new 出這個map
這個Map 存儲的key 就是你定義ThreadLocal 對象 Value 就是賦的值 因爲不是static 的 如果那個對象被new 了 兩次的話 一個類的ThreadLocal對象不會在一個線程裏面共享了。
public class ThreadLocalDog {
ThreadLocal<String> threadLocal=new ThreadLocal<String>();
}
public class ThreadLocalDogStatic {
static ThreadLocal<String> threadLocal=new ThreadLocal<String>();
}
public class ThreadLocalTest {
public static void main(String[] args) {
ThreadLocalDog threadLocalDog=new ThreadLocalDog();
threadLocalDog.threadLocal.set("小黃");
ThreadLocalDog threadLocalDog1=new ThreadLocalDog();
System.out.println(threadLocalDog1.threadLocal.get());
ThreadLocalDogStatic.threadLocal.set("小static");
System.out.println(ThreadLocalDogStatic.threadLocal.get());
threadLocalDog.remove();
threadLocalDog1.remove();
}
}
輸出結果就顯而易見了
null
小static