Are static fields open for garbage collection?

前端 未结 6 1062
谎友^
谎友^ 2020-11-22 13:02

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

class MyUtils {
   private static MyObject myObject = new MyObject();
   /*package*/s         


        
6条回答
  •  失恋的感觉
    2020-11-22 13:59

    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.

提交回复
热议问题