Are static fields open for garbage collection?

51,132

Solution 1

Static variables cannot be elected for garbage collection while the class is loaded. They can be collected when the respective class loader (that was responsible for loading this class) is itself collected for garbage.

Check out the JLS Section 12.7 Unloading of Classes and Interfaces

A class or interface may be unloaded if and only if its defining class loader may be reclaimed by the garbage collector [...] Classes and interfaces loaded by the bootstrap loader may not be unloaded.

Solution 2

Static variables are referenced by Class objects which are referenced by ClassLoaders -so unless either the ClassLoader drops the Class somehow (if that's even possible) or the ClassLoader itself becomes eligible for collection (more likely - think of unloading webapps) the static variables (or rather, the objects they reference) won't be collected.

Solution 3

myObject is a reference and not an object. An object is automatically garbage collected when no reference points to it because it is unreachable.

So also the object behind a static reference "myObject" can be garbage collected if you dereference it with

myObject = null;

and there are no other references to this object.

However static references and variables remain for the lifetime of your program.

Solution 4

If you want a temporary object to be used for static initialisation then disposed of, you can use a static initialiser block, e.g.

class MyUtils {
   static
   {
      MyObject myObject = new MyObject();
      doStuff(myObject, params);
   }

   static boolean doStuff(MyObject myObject, Params... params) {
       // do stuff with myObject and params...
   }
}

since the static initialiser block is a special kind of static method, myObject is a local variable and can be garbage collected after the block finishes executing.

Solution 5

I think this answers your question - basically not unless the class comes from a special class loader and that unloads the class.

Share:
51,132
Michael Deardeuff
Author by

Michael Deardeuff

I make large (really large) web services. My primary task is to make them robust (but I also go for easy-to-use). Thread concurrency? That's the easy stuff. I'm talking about large-scale distributed systems. I also love, love, love a good data structure.

Updated on July 08, 2022

Comments

  • Michael Deardeuff
    Michael Deardeuff almost 2 years

    Given an hypothetical utility class that is used only in program setup:

    class MyUtils {
       private static MyObject myObject = new MyObject();
       /*package*/static boolean doStuff(Params... params) {
           // do stuff with myObject and params...
       }
    }
    

    will myObject be garbage collected when it is no longer being used, or will it stick around for the life of the program?