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

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

问题描述

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

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

myObject会在不再使用时被垃圾回收,还是会在程序的整个生命周期中继续使用? / p>

解决方案

加载类时,无法为垃圾收集选择静态变量。它们可以在各自的类加载器(负责加载这个类)自己收集垃圾时收集。



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


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



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?

解决方案

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.

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

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