Knight
Knight

Reputation: 573

Total free memory java

I'm wondering why total free memory doesn't change after creating big table. But when I use garbage collector total free memory increases.

import java.util.Random;

public class Main{
 public static void main(String[] args) throws Exception
 {
    C c = new C();

    System.out.println("Free memory: "+Runtime.getRuntime().freeMemory());
    c.CreateTable();
    System.out.println("Free memory: "+Runtime.getRuntime().freeMemory());
    System.gc();
    System.out.println("Free memory: "+Runtime.getRuntime().freeMemory());
 }
}


class C{
 public void createTable()
 {
    int[] ar = new int[70000];
    Random r = new Random();
    for(int i = 0; i<ar.length;i++)
    {
        ar[i]=r.nextInt(99);
    }
 }
}

Upvotes: 3

Views: 138

Answers (2)

Surbhi Sharma
Surbhi Sharma

Reputation: 119

This is because JVM created int[] ar in TLAB (thread-local allocation buffer).Let me explain this with the following example:

1) Suppose total memory in the system was 100 units.

2) The current thread has already created a TLAB beofre even a single line of code has run.

3) TLAB's memory(say 10 units) is already deducted from the total memory i.e (Runtime.freeMemory shows 90 units)

4) int[] ar is created inside TLAB as TLAB has free space.

5) After creating of int[] ar running Runtime.freeMemory showed 90 units ( as it is created inside the TLAB).

6) Now on doing GC you get to see 100 units again

Upvotes: 2

Stephen C
Stephen C

Reputation: 719436

I can't reproduce the behavior you claim is occurring:

$ java Main 
Free memory: 126206592
Free memory: 125535432
Free memory: 125943720

As you can see, the free memory reduces after calling createTable() and then increases again after calling System.gc().

Now you don't get all of the allocated memory back1, but there are lots of possible explanations for that including:

  • extra classes may have been loaded resulting in increased heap usage
  • some code may have been JIT compiled resulting in increased heap usage
  • objects may have been allocated in a region of the heap that is collected infrequently. For example, a large array may be allocated directly into tenured space ...

Summary: Java memory allocation / garbage collection is complicated ... and beginners are better off2 not trying to figure out how it works using simple (naive) "black box" tests. You will learn more by finding / reading articles.


1 - To be precise, the GC may be reclaiming all of the memory that the call explicitly allocated ... but there are other things going on that mean that this is not reflected in the "free space" figure.

2 - If your head explodes, it will leave nasty stains on the carpet ..... :-)

Upvotes: 1

Related Questions