2011-06-02 6 views
10

Javaプログラムで使用できるメモリの量を計算しようとしています。 私はこの現在の実装を持っています:Javaで利用可能なメモリを計算する最良の方法は何ですか?

long getAvailableMemory() { 
    Runtime runtime = Runtime.getRuntime(); 
    long totalMemory = runtime.totalMemory(); 
    long freeMemory = runtime.freeMemory(); 
    long maxMemory = runtime.maxMemory(); 
    long usedMemory = totalMemory - freeMemory; 
    long availableMemory = maxMemory - usedMemory; 
    return availableMemory; 
} 

そうですか?この情報をより簡単に、より正確に計算する方法はありますか?誰か他のコードを見た後、少し違うこのようなものを見ました:

long getAvailableMemory() { 
    long totalVmHeap = Runtime.getRuntime().totalMemory(); 
    long freeVmHeap = Runtime.getRuntime().freeMemory(); 
    long usedVmHeap = totalVmHeap - freeVmHeap; 
    long maxVmHeap = Runtime.getRuntime().maxMemory(); 
    long availableVmHeap = maxVmHeap - usedVmHeap + freeVmHeap; 
    return availableVmHeap; 
} 

とにかく、この情報を得るにはどうすればよいですか?

+1

をあなたの解決策は、私には正しく見えます。 – Adrian

+0

私は彼らが同じだと思ったが、今では2番目のものがあなたに(最大 - 合計)を与えることが分かる。 – trutheality

+1

私は答えとしてあなたの質問の一部を入れなければならないと思うので、これは答えられた質問として提出することができます。 [私自身の質問に答えてください](http://meta.stackexchange.com/questions/12513/should-i-not-answer-my-own-questions) – Jarekczek

答えて

8

あなたのソリューションは、(あなたが計算しているかを説明するには、以下のコメント)私には正しいよう:

long getAvailableMemory() { 
    Runtime runtime = Runtime.getRuntime(); 
    long totalMemory = runtime.totalMemory(); // current heap allocated to the VM process 
    long freeMemory = runtime.freeMemory(); // out of the current heap, how much is free 
    long maxMemory = runtime.maxMemory(); // Max heap VM can use e.g. Xmx setting 
    long usedMemory = totalMemory - freeMemory; // how much of the current heap the VM is using 
    long availableMemory = maxMemory - usedMemory; // available memory i.e. Maximum heap size minus the current amount used 
    return availableMemory; 
} 

私はあなたのユースケースが何であるかはよく分からないが、あなたが望むかもしれないヒープ内の限界もありますPermGenサイズのように見えるように:How do I programmatically find out my PermGen space usage?

関連する問題