首页 > 解决方案 > How JVM manages memory for methods?

问题描述

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.

标签: javamemorymemory-managementstaticjvm

解决方案


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.


推荐阅读