Java虛擬機器(3)自動記憶體管理機制,java虛擬機器

來源:互聯網
上載者:User

Java虛擬機器(3)自動記憶體管理機制,java虛擬機器
概要

在Java技術體系中,自動記憶體管理最終可以歸結為自動化地解決了兩個問題:給對象分配記憶體以及回收分配給對象的記憶體。

本文主要探討給對象分配記憶體這點事。對象的記憶體配置,往大的方向上講,就是在堆上分配。但是也有一些情況會在棧上分配和在TLAB上分配等。所以分配的規則並不是百分百固定的,其細節取決於當前使用的是哪一種GC組合和虛擬機器中與記憶體相關的參數的設定。



本文主要介紹幾條最普遍的記憶體配置規則,並結合代碼來驗證這些規則。常見的記憶體配置規則有以下幾條: 
  • 對象優先分配在Eden分配
  • 大對象直接進入老年代
  • 長期存活的對象進入老年代
  • 動態對象年齡判定
    先來看一副圖   


現代商業虛擬機器都將Java堆分為新生代和老年代,在新生代中,一般採用複製演算法。在老年代中,一般採用標記-整理演算法。

新生代的堆空間又劃分為一塊較大的Eden空間和兩塊較小的Survivor空間如所示,每次只使用Eden和其中的一塊Survivor(因為採用複製演算法,所以另外一塊Survivor拿來做保留地區)。HotSpot虛擬機器預設Eden和Survivor的大小比例為8:1,就是說每次新生代中可用記憶體空間為整個新生代容量的90%,只有10%的記憶體是會被“浪費”的。當然,98%的對象可回收只是一般情境下的資料,我們沒有辦法保證每次回收都只有不多於10%的對象存活,當Survivor空間不夠用時,需要依賴其他記憶體(這裡指老年代)來進行分配擔保,一般情況下的GC策略如:


廢話少說,下面開始本文

  對象優先分配在Eden分配

先運行下面代碼,然後結合日誌來分析。以下代碼的開頭都注釋了執行時所需要設定的虛擬機器啟動參數,這些參數對實驗結果有直接影響,請調試代碼的時候不要忽略掉.本例子介紹的比較詳細,後面幾個例子中重複的內容就不在細講。

public class TestGC1 {       private static final int _1MB = 1024*1024;       /**       * VM ARGS: -verbose:gc - Xms20m -Xmx20m -Xmn10m - XX:SurvivorRatio=8 -XX:+PrintGCDetails       */       public static void testAllocation(){             byte[] allocation1, allocation2,allocation3 ,allocation4;            allocation1 = new byte [2 * _1MB];            allocation2 = new byte [2 * _1MB];            allocation3 = new byte [2 * _1MB];            allocation4 = new byte [4 * _1MB];      }       public static void main(String[] args) {             testAllocation();      }}


查看輸出日誌


先解釋一下各個參數的意義:
-verbose:gc 表示輸出虛擬機器中的GC的情況 (紅色方框部分)
-Xms20m 表示初始堆初始值
-Xmx20m 表示初始堆最大值 (- Xms和-Xmx的值相等時,表明堆空間大小為20m且不可擴充)
-Xmn10m 表示老年代的堆大小
-XX:SurvivorRatio=8 表明新生代中Eden區和Survivor區的空間比例為8:1
-XX:+PrintGCDetails 列印GC詳細情況 (藍色方框部分)


 

在testAllocation()方法中,嘗試分配3個2MB大小和1個4MB大小的對象。當分配allocation4對象時候發生一次Minor GC.詳細情況看日誌(紅色方框部分),關於各個數位解釋參考http://blog.csdn.net/alivetime/article/details/6895537  。這次GC的結果是新生代從6487KB變為149KB,而總記憶體佔用量則幾乎沒有減少(因為allocation1,allocation2,allocation3三個對象都依舊存活)。這次Minor GC發生的原因是給allocation4分配記憶體的時候,發現Eden已經被佔用了6MB,剩下的2MB不足已指派,因此發生Minor GC.
GC期間虛擬機器又發現已有的3個2MB大小的對象無法存入Survior空間,所以只好通過分配擔保機制提前轉移到老年代中去。
此時,老年代的空間為10MB足夠分配給3個2MB大小的對象,因此不會執行Full GC
接下來,虛擬機器又會查看HandlePromotionFailure設定是否允許擔保失敗,預設設定為ture。所以最終執行Minor GC。執行過程如紅色線頭所示


這次GC結束後,4MB的allocation4對象被順利分配在Eden中。因此程式執行完的結果是Eden佔用4MB,Survivor空間,老年代被佔用6MB。

  大對象直接進入老年代 先運行代碼並輸出日誌 
public class TestGC2 {       private static final int _1MB = 1024*1024;       /**       * VM ARGS: - verbose:gc - Xms20m -Xmx20m - Xmn10m - XX:SurvivorRatio=8 - XX:+PrintGCDetails       * - XX:PretenureSizeThreshold=3145728       */       public static void testPretenureSizeThreshold(){             byte [] allocation;            allocation = new byte [4 * _1MB];      }       public static void main(String[] args) {             testPretenureSizeThreshold();      }}


輸出GC日誌如下  Heap   def new generation   total 9216K, used 507K [0x315e0000, 0x31fe0000, 0x31fe0000)    eden space 8192K,   6% used [0x315e0000, 0x3165ef18, 0x31de0000)    from space 1024K,   0% used [0x31de0000, 0x31de0000, 0x31ee0000)    to   space 1024K,   0% used [0x31ee0000, 0x31ee0000, 0x31fe0000)   tenured generation   total 10240K, used 4096K [0x31fe0000, 0x329e0000, 0x329e0000)     the space 10240K,  40% used [0x31fe0000, 0x323e0010, 0x323e0200, 0x329e0000) 

虛擬機器提供了一個- XX:PretenureSizeThreshold參數,令大於這個設定的對象直接分配到老年代中。所以在testPretenureSizeThreshold()方法中 4MB的allocation對象被之間分配到老年代中。日誌紅色部分證明這一點

  長期存活的對象進入老年代

為了能夠識別哪些對象應當放在新生代,哪些對象應該放在老年代,虛擬機器給每個對象定義了一個對象年齡技術器。
如果對象在Eden出生並經過第一次Minor GC後仍然能夠存活,並且能被Survivor容納的話,將被移動到Survivor空間中,並將對象年齡設為1.對象在Survivor中每熬過一次MinorGC,年齡就增加1歲,當它的年齡增加到一定程度(預設為15歲),就會被晉陞到老年代中。對象晉陞到老年代的年齡閾值,可以通過參數-XX:MaxTenuringThreshold來設定。

下面分別以   MaxTenuringThreshold=1和   MaxTenuringThreshold=15運行下面代碼並輸出GC日誌  
public class TestGC3 {       private static final int _1MB = 1024*1024;       /**       * VM ARGS: - verbose:gc - Xms20m -Xmx20m - Xmn10m - XX:SurvivorRatio=8 - XX:+PrintTenuringDistribution       * - XX:MaxTenuringThreshold=1 - XX:+PrintGCDetails       */       public static void testMaxTenuringThreshold(){             byte [] allocation1, allocation2,allocation3 ;            allocation1 = new byte [ _1MB / 4];            allocation2 = new byte [ _1MB * 4];            allocation3 = new byte [ _1MB * 4];            allocation3 = null ;            allocation3 = new byte [ _1MB * 4];      }       public static void main(String[] args) {             testMaxTenuringThreshold();      }


以MaxTenuringThreshold=1運行輸出日誌

[GC [DefNew    Desired survivor size 524288 bytes, new threshold 1 (max 1)    - age   1:     415288 bytes,     415288 total    : 4695K->405K(9216K), 0.0064338 secs] 4695K->4501K(19456K), 0.0064885 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]    [GC [DefNew    Desired survivor size 524288 bytes, new threshold 1 (max 1)    - age   1:        136 bytes,        136 total    : 4665K->0K(9216K), 0.0013172 secs] 8761K->4501K(19456K), 0.0013602 secs] [Times: user=0.00 sys=0.02, real=0.02 secs]    Heap     def new generation   total 9216K, used 4260K [0x315e0000, 0x31fe0000, 0x31fe0000)      eden space 8192K,  52% used [0x315e0000, 0x31a08fe0, 0x31de0000)      from space 1024K,   0% used [0x31de0000, 0x31de0088, 0x31ee0000)      to   space 1024K,   0% used [0x31ee0000, 0x31ee0000, 0x31fe0000)     tenured generation   total 10240K, used 4501K [0x31fe0000, 0x329e0000, 0x329e0000)       the space 10240K,  43% used [0x31fe0000, 0x32445578, 0x32445600, 0x329e0000)   

以MaxTenuringThreshold=15運行輸出日誌

[GC [DefNew    Desired survivor size 524288 bytes, new threshold 15 (max 15)    - age   1:     415288 bytes,     415288 total    : 4695K->405K(9216K), 0.0064799 secs] 4695K->4501K(19456K), 0.0065357 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]    [GC [DefNew    Desired survivor size 524288 bytes, new threshold 15 (max 15)    - age   1:        136 bytes,        136 total    - age   2:     415080 bytes,     415216 total    : 4665K->405K(9216K), 0.0011127 secs] 8761K->4501K(19456K), 0.0011722 secs] [Times: user=0.01 sys=0.00, real=0.02 secs]    Heap     def new generation   total 9216K, used 4665K [0x315e0000, 0x31fe0000, 0x31fe0000)      eden space 8192K,  52% used [0x315e0000, 0x31a08fe0, 0x31de0000)      from space 1024K,  39% used [0x31de0000, 0x31e455f0, 0x31ee0000)      to   space 1024K,   0% used [0x31ee0000, 0x31ee0000, 0x31fe0000)     tenured generation   total 10240K, used 4096K [0x31fe0000, 0x329e0000, 0x329e0000)       the space 10240K,  40% used [0x31fe0000, 0x323e0010, 0x323e0200, 0x329e0000)   

在方法testMaxTenuringThreshold()中,對象allocation1需要256KB的記憶體空間。當MaxTenuringThreshold=1時,allocation1對象在第二次GC發生時進入老年,新生代的Survivor空間變為0KB。
當MaxTenuringThreshold=15時,allocation1對象在第二次GC發生時仍然留在新生代,新生代的Survivor空間變為404KB

    動態對象年齡判定

為了能更好地適應不同程式的記憶體情況,虛擬機器並不總是要求對象的年齡必須達到MaxTenuringThreshold才能晉陞老年代。如果在Survivor空間中相同年齡所有對象大小的總和大於Survivor空間的一半,年齡大於或等於該年齡的對象就可以直接進入老年代,無須等到MaxTenuringThreshold要求的年齡。
運行下面代碼並輸出GC日誌

public class TestGC4 {       private static final int _1MB = 1024*1024;       /**       * VM ARGS: - verbose:gc - Xms20m -Xmx20m - Xmn10m - XX:SurvivorRatio=8 - XX:+PrintTenuringDistribution       * - XX:MaxTenuringThreshold=1 - XX:+PrintGCDetails       */       public static void testMaxTenuringThreshold(){             byte [] allocation1, allocation2,allocation3 ,allocation4;            allocation1 = new byte [ _1MB / 4];            allocation2 = new byte [ _1MB / 4];            allocation3 = new byte [ _1MB * 4];            allocation4 = new byte [ _1MB * 4];            allocation4 = null ;            allocation4 = new byte [ _1MB * 4];      }       public static void main(String[] args) {             testMaxTenuringThreshold();      }}


輸出GC日誌

[GC [DefNew      Desired survivor size 524288 bytes, new threshold 1 (max 15)      - age   1:     677448 bytes,     677448 total      : 4951K->661K(9216K), 0.0066603 secs] 4951K->4757K(19456K), 0.0067187 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]      [GC [DefNew      Desired survivor size 524288 bytes, new threshold 15 (max 15)      - age   1:        136 bytes,        136 total      : 4921K->0K(9216K), 0.0014790 secs] 9017K->4757K(19456K), 0.0015298 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]      Heap       def new generation   total 9216K, used 4260K [0x315e0000, 0x31fe0000, 0x31fe0000)        eden space 8192K,  52% used [0x315e0000, 0x31a08fe0, 0x31de0000)        from space 1024K,   0% used [0x31de0000, 0x31de0088, 0x31ee0000)        to   space 1024K,   0% used [0x31ee0000, 0x31ee0000, 0x31fe0000)       tenured generation   total 10240K, used 4757K [0x31fe0000, 0x329e0000, 0x329e0000)         the space 10240K,  46% used [0x31fe0000, 0x32485588, 0x32485600, 0x329e0000)     

在日誌中,我們發現Survivor空間的使用率為0,也就是說allocation1 ,allocation2對象都進入到了老年代中,而沒有等到15歲的年齡。


---------------------------------------------全文完----------------------------------------------------

著作權聲明:感覺我寫的還算不錯的的話希望你能夠動動你的滑鼠和鍵盤為我點上一個贊或是為我奉獻上一個評論,在下感激不盡!_______________________________________________________歡迎轉載,希望在你轉載的同時,添加原文地址,謝謝配合

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.