无法解决共享对象的更新问题。(引用于《阿里巴巴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