英文:
How does java object with no of state fields get stored in JVM?
问题
示例类
************ Example.java ************
public class Example {
public static void main(String[] args) {
Test test = new Test();
test.hello();
}
}
************** Test.java ************
public class Test {
public void hello() {
System.out.println("Hi");
}
}
**我的理解:** 在 `Example` 类的 `main` 方法中,`test` 引用将被存储在 Java 栈内存中,由于 `new Test()` 对象没有状态,因此不会有任何堆内存分配。
**疑问:** 通常我们说对象被存储在堆内存中,但是这里对于 Test 对象我们没有任何状态字段,那么在堆内存中会有任何内存分配吗?
英文:
Example Classes
************ Example.java ************
public class Example {
public static void main(String[] args) {
Test test = new Test();
test.hello();
}
}
************** Test.java ************
public class Tets {
public void hello() {
System.out.println("Hi");
}
}
My Understanding: In Example.Main
method, test reference will get stored in Java stack memory and Since new Test()
Object has no state so There won't be any Heap memory allocation.
Doubt: Usually We say that Objects get stored in Heap memory but here we don't have any state fields for Test Object, Then will there be any memory allocation in Heap Memory?
答案1
得分: 3
会在堆中创建一个实例,即使没有字段;此外,为该实例创建2个标题:mark
和class
。毕竟,在实例上调用了hello
,而且Java语言规范明确表示对象实例是在堆中创建的。
当代码运行足够多次时,JIT编译器会启动 - 在某个时候,它可能会证明某个实例可能不是必需的,并且可能会消除该分配。或者,如果实例完全是局部的并且没有逃逸,可能会发生一种称为“标量替换”的优化,当实例可以分解为字段时,它不会在堆中分配。
英文:
There will be an instance created in the heap, even if there are no fields; additionally there will be 2 headers for this instance created : mark
and class
. You are calling hello
on an instance after all and the java language specification explicitly says that Object instances are created in the heap.
When the code runs enough times, JIT will kick in - at some point, it might prove that a certain instance might not be needed and might elide that allocation away. Or, if the instance is purely local and does not escape an optimization called scalar replacement might happen, when an instance could be dissolved into fields, and not allocated in the heap.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论