Are static fields open for garbage collection?

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

    The key here is the Garbage Collection of Class instances i.e. Objects. ClassLoader instance is, in essence, an Object. So if the Classloader object is not garbage collected, any references of them stored in heap (i.e. static stuff) will almost never be garbage collected. The exception is String pool.

    So before you suddenly decide to do private static MyGiantClass myGiantObject = new MyGiantClass() Think twice as I have learnt the hard way.

提交回复
热议问题