Java对象如果没有状态字段,如何存储在JVM中?

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

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个标题:markclass。毕竟,在实例上调用了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.

huangapple
  • 本文由 发表于 2020年7月25日 06:46:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/63082363.html
匿名

发表评论

匿名网友

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

确定