静态字段是否对垃圾收集开放? [英] Are static fields open for garbage collection?

查看:32
本文介绍了静态字段是否对垃圾收集开放?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个仅在程序设置中使用的假设实用程序类:

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...
   }
}

当 myObject 不再被使用时,它会被垃圾回收,还是会在程序的生命周期内一直存在?

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

推荐答案

在加载类时无法为垃圾回收选择静态变量.当相应的类加载器(负责加载这个类)本身被收集为垃圾时,它们可以被收集.

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.

查看 JLS 第 12.7 节卸载类和接口

一个类或接口可能被卸载当且仅当它的定义类loader 可能会被垃圾回收收集器 [...] 类和接口由引导加载程序加载的可能不会被卸载.

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.

这篇关于静态字段是否对垃圾收集开放?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆