西海岸より

つらつらざつざつと

ヒープを意図的に増加させる

ヒープサイズを意図的に圧迫するために作成した際に作ったjavaのメモ。

import java.io.*;
import java.util.*;

public class MemCracker {
    public static void main(String[] args) throws Exception{
        System.out.println("Start MemCracker.");
        StringBuilder sb = new StringBuilder();
        showMemoryStatus(sb);
        BufferedReader br =
            new BufferedReader(new InputStreamReader(System.in));
        
        for (String line = askSize(br); line != null; line = askSize(br)) {
            try {
                if (line.equals("")) continue;
                if (line.equals("e")) break;
                long mbSize = Long.parseLong(line);
                System.out.println("mbSize=" + mbSize);
		sb=new StringBuilder();
                makeMbMessage(mbSize, sb);
                showMemoryStatus(sb);
            } catch (NumberFormatException e) {
                System.out.println("Illegal format. Please enter Number.");
            }
        }
        showMemoryStatus(sb);
        System.out.println("Exit MemCracker.");
    }
    
    private static void showMemoryStatus(StringBuilder sb) {
        System.out.println("-------------------------------");
        System.out.println("String size: " + sb.length());
        Runtime runtime = Runtime.getRuntime();
        long usedMemory = runtime.totalMemory() - runtime.freeMemory();
        System.out.println("Free memory(MB): " + 
            (double)runtime.freeMemory()/(0x1<<20));
        System.out.println("Used memory(MB): " +
            (double)usedMemory/(0x1<<20));
        System.out.println("Total memory(MB): " +
            (double)runtime.totalMemory()/(0x1<<20));
        System.out.println("-------------------------------");
    }
    
    private static String askSize(BufferedReader br) throws IOException {
        System.out.print("Input MB size(e:exit) -> ");
        return br.readLine();
    }
	
    private static void makeMbMessage(long mbSize, StringBuilder sb) {
        for (long i=0; i<mbSize*64*1024; i++) {
            sb.append("0123456789ABCDEF");
        }
    } 
}
  • 実行結果
 java MemCracker
Start MemCracker.
-------------------------------
String size: 0
Free memory(MB): 1.5078887939453125
Used memory(MB): 0.4296112060546875
Total memory(MB): 1.9375
-------------------------------
Input MB size(e:exit) -> 10
mbSize=10
-------------------------------
String size: 10485760
Free memory(MB): 7.739189147949219
Used memory(MB): 54.19831085205078
Total memory(MB): 61.9375
-------------------------------
Input MB size(e:exit) -> 

GCの挙動や、動的ヒープサイズの確保の動作を見るのに利用。