垃圾回收 : static variables not lasting through the applications lifetime

标签 java garbage-collection jvm

我一直被告知静态变量会持续应用程序的整个生命周期,但我刚刚读到这篇关于 javas GC 的文章让我对这个说法产生了疑问:

Classes may get collected (unloaded) if the JVM finds they are no longer needed and space may be needed for other classes. The permanent generation is included in a full garbage collection.

所以问题是什么会导致 JVM 执行此操作,这是否意味着所有静态类变量在某种意义上都被“重置”了?

最佳答案

So the question is what would cause the JVM to do this ...

当一个不再可达时,就会发生这种情况。实际上,只有当应用程序(或框架)动态创建类加载器、动态加载类,然后类加载器、类和这些类的实例都变得无法被应用程序的其余部分访问时,才会发生这种情况。

它不会发生在由应用程序的主要类加载器加载的类上,因为这样的类总是可以访问的。 (例如,通过使用主类加载器调用 ClassLoader.forName(...)。)

... would it mean that all static class variables are in a sense "reset"?

没有。更好的表征是,如果 static 变量属于已卸载的类,则它们已不复存在。 (就像局部变量在超出范围时不复存在一样。)

请注意,这只会在类被卸载时发生。如果应用程序仍然有可能观察有问题的静态变量,那么变量可达就足够了……这将抑制类卸载.

关于垃圾回收 : static variables not lasting through the applications lifetime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48804828/

相关文章:

java - 垃圾收集器是否会收集不再可访问但仍指向树的树叶

java - 运行 Sonar 运行器时超出 GC 开销限制

java - 实现事件驱动的轻量级线程

java - 缩小幸存者空间导致持续的完整 GC

java - Hibernate - 在父表和子表中的列上设置过滤

java - 从 bean factory 访问 injectee 组件

java - constructor-arg 和 property 一起在 bean 定义中

java - 有没有使用antlr4从java源代码创建AST并提取方法、变量和注释的简单示例?

c# - 为什么 Roslyn 中有这么多对象池的实现?

python - 在 Jython 上开发 Django 有问题吗?