5

I have a class that looks like:

  public class BadCodeStyle {

     private static String theAnswer = null;

     public static void setAnswer(String whatsNew) {
         theAnswer = whatsNew;
     }

     public static String getAnswer() {
          return (theAnswer == null) ? "I don't know" : theAnswer;
     }            

  }

Of course that's a simplification of the actual class. What really happens is that the static method retrieves a framework object if the variable is null. Setting the variable just serves to insert a mock value for test runs where I want to isolate the code from the framework (retrofitting code for testability is fun - like poking your own eye type of fun).

When I do BadCodeStyle.setAnswer("42") the static method behaves like a Singleton (?). I did read the classloader explanation and conclude: the variable will stay as long as the class is loaded and that would be as long as the JVM runs? Is that correct?

4

2 回答 2

7

Static class variables live as long as the class definition is loaded. This is usually until the VM exits. However, there are other ways a class can be unloaded. See, for example, this thread and this one.

于 2013-05-30T02:08:44.210 回答
-1

Static variables are common to all objects (shared) more precisely. it doesn't belong to any instance of class (objects). so its obvious that it cannot be garbage collected with objects.

class X
{
    static string str;
}

X obj1 = new X();
X obj2 = new X();

when you define X.str compiler 'll say replace with Class reference.

But it belongs to Class object. we refer to it as Class variable too. (classloader loads the class) so its single variable (singleton 's actually a pattern that uses single object [use private constructors and using a method to return that single object] )

As you read the memory is reclaimed only when the program is done. it doesn't get (reclaimed) garbage collected in between [Non used objects 'll be garbage collected normally] .

so its lifetime exists as long as the process exists [program is running].

checkout lifetime of variables: www.cs.berkeley.edu/~jrs/4/lec/08

于 2013-05-30T02:12:55.203 回答