JVM如何管理方法的内存?

huangapple go评论137阅读模式
英文:

How JVM manages memory for methods?

问题

例如,我们有一个MyClass的实例,它包含1个方法。这个方法应该保留在内存中。当这个MyClass的实例被垃圾回收时,对这个方法的引用是否也被删除了?我想弄清楚通过依赖注入执行所有操作(因此创建每个类的新实例)是否需要更少的内存并且更高效,还是简单的具有大量静态方法的Helper类仍然很好。

英文:

For example we have an instance of MyClass and it contains 1 method. This method should be kept in memory. When this instance of MyClass is being GC'ed, is a reference to this method being deleted as well? I want to figure out weather doing everything via Dependency Injection (hence creating new instances of every class) requires less memory and more efficient or simple Helper classes with a bunch of static methods are still good.

答案1

得分: 1

对象的实例方法存储在其类对象中(应仅存在一份副本),它们不会随每个新实例而“复制”,相反,在幕后,每个实例都持有对存储在类对象中的方法实现的引用。
实例被垃圾回收,而不是类数据。类数据存储在permgen空间或metaspace中,具体取决于Java版本。
垃圾收集器专门在创建实例的堆上工作,而不是在permgen或metaspace上。

英文:

The instance methods of an object are stored in its class object (only one copy should exist), they are not "copied" with each new instance, instead, under the hood each instance holds a reference to the method implementation residing in the class object.
Instances are garbage collected not the class data. The class data gets stored in permgen space or metaspace depending on the java version.
Garbage collectors work specifically on the heap where the instances are created not on the permgen or metaspace.

huangapple
  • 本文由 发表于 2020年8月12日 17:44:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/63373932.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定