Are static fields open for garbage collection?

前端 未结 6 1108
谎友^
谎友^ 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:37

    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.

提交回复
热议问题