Runtime - why is freeMemory() not showing memory consumed correctly?

后端 未结 4 918
天涯浪人
天涯浪人 2021-01-03 04:58

Below is the code snippet to examine the memory

public class TestFreeMemory {

    public static void main(String ... args){

        Runtime rt = Runtime.g         


        
4条回答
  •  执笔经年
    2021-01-03 05:40

    Memory Management on HotSpot JVM:

    Another desirable garbage collector characteristic is the limitation of fragmentation. When the memory for garbage objects is freed, the free space may appear in small chunks in various areas such that there might not be enough space in any one contiguous area to be used for allocation of a large object. One approach to eliminating fragmentation is called compaction, discussed among the various garbage collector design choices below.

    Memory Management in HotSpot JVM (PDF Format).

    This behavior can be very dependent on the particular implementation of the garbage collection. For example:

    Parallel Mark Compact

    • Stop-the-world
    • Heap divided into fixed-size chunks (> 2kb now, will likely increase or be subject to ergonomics)
    • Chunk is unit of live data summarization
    • Parallel mark
    • Record live data addresses in external bitmap
    • Find per chunk live data size
    • Find dense chunks, i.e., ones that are (almost) full of live objects

    I've made this sample (with abusive String concatenation to use up more memory):

    public class TestFreeMemory {
    
     static void allocateSomeMemory(){
      long[][] array = new long[400][400];
     }
    
        public static void main(String ... args){
    
            Runtime rt = Runtime.getRuntime();
    
            allocateSomeMemory(); // once we leave, our array is not reachable anymore 
            System.out.println("Free Memory (Before GC): " + rt.freeMemory());     
            rt.gc();
            System.out.println("Free Memory (After GC): " + rt.freeMemory());
    
            String a = new String("A");
            for(int i = 0; i < 100; i++){
             a+="B";
            }
    
            System.out.println("Free Memory (After String Creation): " + rt.freeMemory());
            // Less free memory expected.
        }
    
    }
    

    Output:

    Free Memory (Before GC): 3751800

    Free Memory (After GC): 5036104

    Free Memory (After String Creation): 5012048


    If I use a relatively small number of iterations in the loop (say 10), the extra space does not show up in freeMemory(), and I'd get something like this:

    Free Memory (Before GC): 3751800

    Free Memory (After GC): 5036040

    Free Memory (After String Creation): 5036040

提交回复
热议问题