淺析Java對象佈局

 

 

此文要分析的問題:Java對象佈局,即Java對象由什麼組成、對象在堆上分配多少內存。

1,至少要考慮實例屬性--不固定,對象中的屬性如。

2,對象頭

3,數據對齊(填充數據),如64bit jvm定義一個類對象必須是8的整數倍。便於計算機編址和尋址。

 

可以使用JOL查看Java 對象佈局

(1)引入jol

<dependency>  
    <groupId>org.openjdk.jol</groupId>  
    <artifactId>jol-core</artifactId>  
    <version>put-the-version-here</version>  
</dependency> 

(2)創建一個非常簡單的L類

public class L {
  int flag;
}

(3)測試

public class Test {
 public static void main(String[] args) {
	 L l=new L();
	 System.out.print( ClassLayout.parseInstance(l).toPrintable());
  }
}

(4)結果

什麼是java的對象頭?

對象的第一個部分,所有對象都有的公共部分

從上面的結果可以看出在64位jvm環境下對象頭佔12byte

java對象頭的組成

我們可以直接訪問http://openjdk.java.net/groups/hotspot/docs/HotSpotGlossary.html查看hotspot實現Jvm規範中對對象頭

object header

Common structure at the beginning of every GC-managed heap object. (Every oop points to an object header.) Includes fundamental information about the heap object's layout, type, GC state, synchronization state, and identity hash code. Consists of two words. In arrays it is immediately followed by a length field. Note that both Java objects and VM-internal objects have a common object header format.

翻譯:

對象頭

每個gc管理的堆對象開頭的公共結構。(每個oop都指向一個對象標頭。)包括堆對象的佈局、類型、GC狀態、同步狀態和標識哈希碼的基本信息。由兩個詞組成。在數組中,它後面緊跟着一個長度字段。注意,Java對象和vm內部對象都有一個通用的對象頭格式。

(1)64位jvm環境java對象頭中的mark word佔64bit

The first word of every object header. Usually a set of bitfields including synchronization state and identity hash code. May also be a pointer (with characteristic low bit encoding) to synchronization related information. During GC, may contain GC state bits

 

翻譯:每個對象標頭的第一個單詞。通常是一組位域,包括同步狀態和標識哈希碼。也可以是同步相關信息的指針(具有特徵的低比特編碼)。在GC期間,可能包含GC狀態位。

(2)klass pointer/class metadat address正常情況佔64bit,當開啓指針壓縮佔32bit

The second word of every object header. Points to another object (a metaobject) which describes the layout and behavior of the original object. For Java objects, the "klass" contains a C++ style "vtable".

翻譯:每個對象標頭的第二個單詞。指向描述原始對象的佈局和行爲的另一個對象(元對象)。對於Java對象,“klass”包含一個c++風格的“vtable”。

(3)數組長度

當屬性中存在數組時需要。

總結圖:

 

注:

jvm--(虛擬機規範) 

hotspot,j9,taobaovm等虛擬機(根據規範實現的產品)

openJdk 項目--開源的hotspot代碼/c++

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章