What is the lifespan of a static variable

大城市里の小女人 提交于 2020-01-21 19:15:07

问题


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
}

Edit

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)?


回答1:


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.)



来源:https://stackoverflow.com/questions/23436096/what-is-the-lifespan-of-a-static-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!