Java メモリー使用量を取得する方法

デバックやシステムの最適化などの作業では、メモリの情報が重要になることがあります。
Java 仮想マシンのメモリ情報について、得られる情報は次のようになります。

合計 Runtime.getRuntime().totalMemory()
Java仮想マシンへの割り当てメモリ
使用量 Runtime.getRuntime().freeMemory()
割り当てられたオブジェクトの空きメモリ
使用量 Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()
現在メモリに割り当てられたオブジェクトのメモリ使用量
使用可能最大 Runtime.getRuntime().maxMemory()
Java仮想マシンが使用を試みる最大メモリ容量

使用量が合計に近づき、かつガベージコレクションでも空きメモリが確保できない場合、Java仮想マシンは「使用可能最大」までメモリを拡張します。

サンプルコード

private final static String TAG = "Memory Infomation";

public static String getMemoryInfo() {
    String info = "";
    
    DecimalFormat format_mem =   new DecimalFormat("#,###KB");
    DecimalFormat format_ratio = new DecimalFormat("##.#");
    long free =  Runtime.getRuntime().freeMemory() / 1024;
    long total = Runtime.getRuntime().totalMemory() / 1024;
    long max =   Runtime.getRuntime().maxMemory() / 1024;
    long used =  total - free;
    double ratio = (used * 100 / (double)total);

    info += "Total   = " + format_mem.format(total);
    info += "\n";
    info += "Free    = " + format_mem.format(total);
    info += "\n";
    info += "use     = " + format_mem.format(used) + " (" + format_ratio.format(ratio) + "%)";
    info += "\n";
    info += "can use = " + format_mem.format(max);
    return info;
}

public static void viewMemoryInfo() {
    Log.d(TAG,"---------- MemoryInfo --------");
    Log.d(TAG,getMemoryInfo());
    Log.d(TAG,"------------------------------");
}

関連記事

スポンサーリンク

WHERE句 抽出条件や結合条件を追加する

ホームページ製作・web系アプリ系の製作案件募集中です。

上に戻る