New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
ThreadLocal 表述错误 #975
Comments
感谢👍可以提交一下PR不? |
你可以能理解有问题,Entry是将key作为被弱引用的对象,value作为强引用,因此key是会被回收的,但是value不会被回收。如下例子,car是强引用,但是我们不会直接使用car,而是使用被包装的的entry.car,它是弱引用,会被回收: public static void main(String[] args) {
// baseWeak();
Car car = new Car(22000, "sliver");
Entry entry = new Entry(car, new Object());
int i = 0;
new Thread(() -> {
while (true) {
System.gc();
}
}).start();
while (true) {
if (entry.get() != null) {
i++;
System.out.println("Object is alive for " + i + " loops - " + entry);
} else {
// Object is alive for 61441 loops - Entry@490d6c15
// null,java.lang.Object@7d4793a8
// Object has been collected.
System.out.println(entry.get() + "," + entry.getValue());
System.out.println("Object has been collected.");
break;
}
}
}
class Car {
private double price;
private String colour;
public Car(double price, String colour) {
this.price = price;
this.colour = colour;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getColour() {
return colour;
}
public void setColour(String colour) {
this.colour = colour;
}
}
class Entry extends WeakReference<Car> {
/**
* The value associated with this ThreadLocal.
*/
Object value;
Entry(Car k, Object v) {
super(k);
value = v;
}
public Object getValue() {
return value;
}
} 我的机器稳定在第6W次轮询就会出现null。 |
@LiWenGu 感谢回复.
我的意思是, 当外部方法调用 |
@ZacBi
你最后贴的图有点不懂,"强引用仍然存在于本地变量表"这句话的意思是该对象是栈上分配吗? |
您这话说的就有点火箭味十足,说话确实得要依据,但是我跟你说的也是根据我的经验结论。要证明的话专门搞JVM的人估计可以给你解释清楚,比如你可以去知乎找R大这种JVM大牛。ps:我还没战术后仰呢,你就说我章口就来。既然你觉得我是胡诌乱造没有依据,那你可以关注下这个问题:https://stackoverflow.com/questions/64783413/why-this-object-with-strong-reference-will-be-recycled#comment114542031_64783413 按目前的阶段的讨论可能是JIT的优化越过了可达性分析的判断。 |
@LiWenGu 感谢您的答复, 讨论是有点冲动了, 向您道歉. |
ref: 万字详解ThreadLocal关键字
key本身就是
ThreadLocal
对象的引用, 是一个强引用,ThreadLocal
并不继承自WeakReference
, 而是ThreadLcoalMap.Entry
继承自WeakReference
.下面GC关于key的内容也需要改改.还有能把
类
和对象
的后缀加上么, 看的有点难受.The text was updated successfully, but these errors were encountered: