kyle shanks
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- title: 'JVM 崩潰測試 - OOM' disqus: kyleAlien --- JVM 崩潰測試 - OOM === ## OverView of Content 以下使用 eclipse Java IDE,並透過調整編譯運行參數 (VM argument) 來測試 JVM `OutOfMemoryError` 異常 > ![](https://i.imgur.com/XEJsLuk.png) [TOC] ## JVM 內存分配 :::success 詳細請看 [**Java 內存策略**](https://hackmd.io/12h2jhr3RM-0jm8Wduxk9g?view#Java-%E5%85%A7%E5%AD%98-amp-OOM) 篇 ::: > ![](https://i.imgur.com/S8yNFMB.png) ## Java 堆 首先關注物件最常存在的區域 **Java 堆**,通常也就是這個區塊造成的 OOM ### Java 堆溢出 - OutOfMemoryError * 首先設定 `VM argument` 限制 Java 堆的大小改為不可拓展 (上下線設置相同),並在 Heap 崩潰時,會匯出崩潰資訊 | 參數 | 功能 | | -------- | -------- | | -Xms20m | Heap 最小值設定為 20m | | -Xmx20m | Heap 最大值設定為 20m | | -XX:+HeapDumpOnOutOfMemoryError | Heap 崩潰時,會匯出崩潰資訊 | * Java 堆溢出很容易,只要不斷創建對象即可,不過該對象必須要有連結,否則會被 GC 回收;以下使用 ArrayList 連接所有對象 ```java= public class HeapOOM { private static final class OOMObject { } public static void main(String[] args) { List<OOMObject> list = new ArrayList<>(); while(true) { list.add(new OOMObject()); } } } ``` > ![](https://i.imgur.com/dPhk0c9.png) * 錯誤輸出在專案根目錄下,副檔名為 `.hprof` > ![](https://i.imgur.com/qRuba51.png) * 可以使用 `MemoryAnalyzer` 查看 > ![](https://i.imgur.com/epTEfAm.png) ## 虛擬機 & 本地方法棧 本地方法對於 Hotspot 來講沒有區分本地方法、虛擬機棧,**只能透過 `-Xss` 來設置** :::warning 雖然有 `-Xoss` 參數來限制本地方法,但是在 Hotspot 內沒有用 ! (因為它沒實現) ::: ### 虛擬機棧 - Heap 深度 StackOverflow * 關於 JVM 棧的異常有兩種 1. **StackOverflow 異常** (目前說明狀況):Thread 請求的棧深度大於 JVM 規定,就會拋出此異常 2. **OutOfMemoryError 異常**:如果使用的 JVM 棧允許動態擴展,當無法申請到拓展內存時,就會拋出此異常 :::danger * HotSpot 預設是無法動態拓展的; > 像是 `Classic 虛擬機` 就可以調整 * 除了 Thread 以外,Thread 大部分會拋出 `StackOverflow` 異常,除非在最一開始申請 Thread 物件時失敗會拋出 `OutOfMemoryError` ::: * 設定棧參數 `VM argument` 限定其大小 | 參數 | 功能 | | -------- | -------- | | -Xss180k | Stack 深度設定設定為 180k | :::warning * **每個 OS 平台下對應的 JVM Stack 最小深度也不同** ::: * 透過遞迴呼叫來產生 StackOverflow 問題 ```java= public class JavaSMStackSOF { private int stackDeep = 0; public void parser(String str) { ++stackDeep; System.out.println("Deep: " + stackDeep); parser(str); } public static void main(String[] args) { JavaSMStackSOF s = new JavaSMStackSOF(); s.parser("StackOverflow"); } } ``` > ![](https://i.imgur.com/XXZD6Zi.png) ### 虛擬機棧 - 方法區 StackOverflow * 當 Thread 執行函數時,會分配一個 **棧楨** 大小,**當超出棧楨大小時,就會出現 StackOverflow 錯誤** * 設定棧參數 `VM argument` 限定其大小 | 參數 | 功能 | | -------- | -------- | | -Xss180k | Stack 大小設定設定為 180k | :::warning * 每個 OS 平台下對應的 JVM Stack 最小深度也不同 ::: * 設定過多的區域變數,並超出 Stack 限制的大小 ```java= import java.util.Arrays; public class JavaSMStackSOF_2 { private int stackDeep = 0; public void localVar() { long num1, num2, num3, num4, num5, num6, num7, num8, num9, num10, num11, num12, num13, num14, num15, num16, num17, num18, num19, num20, num21, num22, num23, num24, num25, num26, num27, num28, num29, num30, num31, num32, num33, num34, num35, num36, num37, num38, num39, num40, num41, num42, num43, num44, num45, num46, num47, num48, num49, num50, num51, num52, num53, num54, num55, num56, num57, num58, num59, num60, num61, num62, num63, num64, num65, num66, num67, num68, num69, num70, num71, num72, num73, num74, num75, num76, num77, num78, num79, num80, num81, num82, num83, num84, num85, num86, num87, num88, num89, num90, num91, num92, num93, num94, num95, num96, num97, num98, num99, num100; ++stackDeep; localVar(); num1= num2= num3= num4= num5= num6= num7= num8= num9= num10= num11= num12= num13= num14= num15= num16= num17= num18= num19= num20= num21= num22= num23= num24= num25= num26= num27= num28= num29= num30= num31= num32= num33= num34= num35= num36= num37= num38= num39= num40= num41= num42= num43= num44= num45= num46= num47= num48= num49= num50= num51= num52= num53= num54= num55= num56= num57= num58= num59= num60= num61= num62= num63= num64= num65= num66= num67= num68= num69= num70= num71= num72= num73= num74= num75= num76= num77= num78= num79= num80= num81= num82= num83= num84= num85= num86= num87= num88= num89= num90= num91= num92= num93= num94= num95= num96= num97= num98= num99= num100 = 0; } public static void main(String[] args) { JavaSMStackSOF_2 s = new JavaSMStackSOF_2(); s.localVar(); } } ``` :::danger * 不能用 `new` 關鍵字,不然會變為 `OutOfMemoryError` 錯誤 ::: > ![](https://i.imgur.com/XK19dJD.png) ### Thread StackOverflow * 上面有提過每個 Thread 都有自己的 Stack,而對於記憶體來說它占的空間很其實不大,假設 Window 為每個 Process 分配 2G 的空間 > ![](https://i.imgur.com/KHzkZmO.png) 扣除 `方法區`、`Java 堆區` (忽略程序計數器,因為太小) 才是 `本地方法`、`虛擬機 Stack` 的大小 * 設定棧參數 `VM argument` 限定其大小 | 參數 | 功能 | | -------- | -------- | | -Xss100M | Stack 大小設定設定為 100M | ```java= public class JavaVMStackOOM implements Runnable { @Override public void run() { while(true) { // nothing todo } } public void makeThread() { while(true) { new Thread(this).start(); } } public static void main(String[] args) { JavaVMStackOOM s = new JavaVMStackOOM(); s.makeThread(); } } ``` :::danger * 這段程式很危險,可能會造成電腦假死崩潰 但透過 Stack 概念的計算我們可以知道,如果 **想分配更多的 Thread,可以減少 Stack 空間 or 減少 Heap 大小** ::: ## 方法區 & 運行時常量 方法區是運行時常量內的一個區塊,這個兩區塊可以放到一起,如果要使用 String 來測試運行時常量,需要使用 `JDK6` > `JDK7` 部分移除 、`JDK8` 已完全移除 > > ![](https://i.imgur.com/a4xzBoo.png) ### JDK6 - String#intern 常量區溢出 :::info 以下使用 [**`JDK6`**](https://www.oracle.com/tw/java/technologies/javase-java-archive-javase6-downloads.html) 虛擬機測試 ::: * 設定永久區參數 `VM argument` 限定其大小 | 參數 | 功能 | | -------- | -------- | | -XX:MaxPermSize=6M | 永久代最大設為 6M | | -XX:PermSize=6M | 永久代空間設為 6M | * **String#intern 方法**:該方法是一個 Native 方法,並且會將新 String 放置到常量池中 (如果常量池內有相同的,就直接返回),以此方法來來測試方法區崩潰的情況 ```java= import java.util.HashSet; import java.util.Set; public class RuntimeConstantPoolOOM { public static void main(String[] args) { Set<String> set = new HashSet<String>(); int i = 0; while(true) { set.add(String.valueOf(i++).intern()); } } } ``` > ![](https://i.imgur.com/qZMGrZZ.png) :::info * 使用 JDK6 錯誤內容是 `PermGen space` OOM,但如果使用 **JDK7、8 就不會有這個錯誤,因為 JVM 將 字串移至 ++Java 堆++中** ::: ### JDK6 vs. JDK7 - String#intern 比較 * 看看不同 JDK 對於同方法的影響,以下使用不同 JDK 來運行相同程式 (觀察 `String#intern` 方法),測試 JDK 實現的不同造成的影響 ```java= public static void main(String[] args) { String x = "java"; String str1 = new StringBuilder("在這座城市").append("遺失了你").toString(); System.out.println(str1.intern() == str1); String str2 = new StringBuilder("ja").append("va").toString(); System.out.println(str2.intern() == str2); } ``` 1. 使用 JDK6 運行結果:**`String#intern` 拷貝會將所有字符串常量放置永久區**,所以 `在這座城市`、`遺失了你`、`在這座城市遺失了你` 是三個字符串常量,所以一定不同 (第二個比較也一樣) > ![](https://i.imgur.com/dVrOm7Q.png) 2. 使用 JDK7 運行結果:`String#intern` 不用將字符串拷貝到常量區,**字符串連帶對象會放到 Heap 堆區**,所以在第一次出現字符串時才會到字符串放到常量區 * 簡單來說在實際產生字符串前 **`在這座城市`、`遺失了你` 放在 ++堆區++** * 首次調用 `String#intern` 時產生的 **`在這座城市遺失了你` 才放置到 ++常量池++**,`String#intern` 返回的字符串的引用相同 * 也就是首次調用 intern 會才在常量區建立物件,而 `java` 已經在呼叫前建立過,所以 intern 會傳回不同引用 > ![](https://i.imgur.com/1bEqYfD.png) :::info * `java` 字符串之前已經出現過,再次調用 `String#intern` 時產生的引用就會不同 > 也就是常量區會有兩個 `java` 常量,一個是編譯時產生、令一個是運行時產生 ::: ### 方法區 - 主要內容 * Java 方法區會放置 `類名`、`訪問修飾符`、`常量池`、`Field 字段描述`、`Method 方法描述`... 等等 * 如果方法區資料過多就也會產生 OOM ## 本地方法溢出 測試本地方法的呼叫 JVM 是否會產生 OOM ### 本地方法 - OutOfMemoryError * 設定本地方法參數 `VM argument` 限定其大小 | 參數 | 功能 | 補充 | | -------- | -------- | - | | -XX:MaxDirectMemorySize=1M | 設定本地棧大小為 1M | 如果沒有設置就會以棧大小 `-Xmx` 設定為準 | ```java= import sun.misc.Unsafe; import java.lang.reflect.Field; public class DirectMemoryOOM { private static final int _1MB = 1024 * 1024; public static void main(String[] args) throws Exception { Field unsafeField = Unsafe.class.getDeclaredFields()[0]; unsafeField.setAccessible(true); Unsafe unsafe = (Unsafe) unsafeField.get(null); while(true) { unsafe.allocateMemory(_1MB); } } } ``` > ![](https://i.imgur.com/C0iu7gz.png) :::danger * 本地方法 OOM 時匯出檔案的特色 在分析 Dump 出的檔案時最大的特色就是,**啥都沒有 !** 因為 JVM 不會限制到 Native 層的程式 ::: ## Appendix & FAQ :::info ::: ###### tags: `JVM`

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully