Memory Layout of Objects in Java

Ordinary Object Pointers (OOPs)

In Java, each object is allocated memory on the heap.The HotSpot JVM uses a data structure called Ordinary Object Pointers (OOPS) to represent pointers to objects.
All pointers (both objects and arrays) in the JVM are based on a special data structure called oopDesc.
  1. Each oopDesc describes the pointer with the following information:
      • Mark word:
        • The mark word describes the object header. The HotSpot JVM uses this word to store identity hashcode, biased locking pattern, locking information, and GC metadata.
      • Klass word:
        • the klass word encapsulates the language-level class information such as class name, its modifiers, superclass info, and so on.

The layout of memory for an object

  1. Object Header: The first few bytes of memory in an object are used to store its header information. This includes a reference to the object's class, a marker for garbage collection, and other metadata.
the object header consists of mark and klass words plus possible alignment paddings.
  1. Instance Variables: The instance variables of an object are stored in the memory following the object header. These variables are the fields defined in the class, and they are allocated memory based on their type (e.g. int, double, object reference).
  1. Padding: Java requires that each object be aligned to a multiple of 8 bytes. If necessary, padding bytes are added after the instance variables to ensure this alignment.
  1. Object Footer: Some JVMs add an optional footer to the object to help with debugging and profiling. This footer typically contains a checksum or other metadata.

Java对象的访问定位

In Java, when you create an object using the new keyword, the JVM dynamically allocates memory to store the object.
When you create an object in Java, a reference variable is created to refer to the object. This reference variable holds a reference to the memory location where the object is stored. You can use this reference variable to interact with the object and access its methods and fields.
由于reference类型在《Java虚拟机规范》里面只规定了它是一个指向对象的引用,并没有定义这个引用应该通过什么方式去定位、访问到堆中对象的具体位置,所以对象访问方式也是由虚拟机实现而定的

主流的访问方式

  1. 句柄访问:Java堆中将可能会划分出一块内存来作为句柄池,reference中存储的就 是对象的句柄地址,而句柄中包含了对象实例数据与类型数据各自具体的地址信息
notion image
notion image
  1. 直接指针访问:Java堆中对象的内存布局就必须考虑如何放置访问类型数据的相关 信息,reference中存储的直接就是对象地址,如果只是访问对象本身的话,就不需要多一次间接访问的开销
notion image

分析工具

参考/推荐文章

Java垃圾收集Note手写识别模块改进记录
Loading...