静态变量的生命周期是多少 [英] What is the lifespan of a static variable
问题描述
在下面的代码中,Nail
对 ypaw
的引用是否会在我退出方法 someMethod
后立即结束,或者是否有可能泄漏?另外,一旦我退出 Dog
类,对 ypaw
的所有引用都消失了还是 Nail 中的静态引用会导致麻烦?请注意, ypaw
和 mPaw
是同一个对象,我想知道由于静态引用,该对象在内存中存在多长时间.当然假设垃圾收集器在适当的时间执行.
In the following code, does Nail
's reference to ypaw
end as soon as I exit the method someMethod
or is there potential for leakage? Also, once I exit class Dog
are all references to ypaw
gone or does the static reference inside Nail cause troubles? Note that ypaw
and mPaw
are the same object and I am wondering how long the object lives in memory due to the static reference. Of course assume the Garbage Collector executes at the appropriate time.
Class Dog{
private Paw ypaw;
//…..
public void someMethod(){
Nail nail = Nail.getInstance(ypaw);
}
}
Class Nail{
private static Paw mPaw;
public static Nail getInstance(Paw p){
mPaw = p;
return new Nail();
}
//…. other stuff
}
编辑
我的意思是说,我有一个 Dog 实例作为 myDog
,而我的 Nail
实例是通过 myDog
实现的.myDog
死后,mPaw
会发生什么变化(即被 gc'ed)?
I mean to say that I have a single instance of Dog as myDog
and that my single instance of Nail
is through myDog
. What happens to mPaw
after myDog
dies (i.e. is gc'ed)?
推荐答案
不,静态变量的生命周期与加载类的类加载器一样长.所以这在许多应用程序中是永远的".
No, a static variable lives for as long as the classloader which loaded the class does. So that's "forever" in many applications.
不清楚您要实现的目标,但此代码几乎肯定是个坏主意.
It's not clear what you're trying to achieve, but this code is almost certainly a bad idea.
(一般来说,可变静态数据是一个坏主意.可变静态非私有字段是一个真的坏主意 - 除了任何东西之外,您不可能出于同步目的控制所有访问否则.)
(In general, mutable static data is a bad idea. And mutable static non-private fields are a really bad idea - you can't possibly control all access for synchronization purposes, apart from anything else.)
这篇关于静态变量的生命周期是多少的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!