-1

The method is about like this :

public void testGc() {
    char c[] = new char[1024*1024*100] // Allocate 100M memory
    System.gc();
}

But after the method returns, the memory allocated won't be free.

zhongwei
  • 325
  • 1
  • 5
  • 15
  • 2
    You still have a reference to the array... – Manu Nov 27 '15 at 10:59
  • 5
    The whole point of garbage collection is NOT to manually worry about freeing memory. Also, the scope of `c` is not finished yet, so it is not eligible for garbage collection yet. – Jan Dörrenhaus Nov 27 '15 at 11:00

1 Answers1

0

First of, you still have a reference so it won't be freed.

second: calling System.gc() won't free the memory instantly. It just kindly asks the garbage collector if it could clean up.

Philipp Sander
  • 10,139
  • 6
  • 45
  • 78
  • Imagine I have function that declares a lot of memory, when the function is called the memory will be occupied. When the the call ends, will the memory be reversed afterwords or not ? public static void main(String[] args) { ok(); Scanner n = new Scanner(System.in); n.nextLine(); } private static void ok(){ char c[] = new char[1024*1024*200]; // Allocate 100M memory Scanner n = new Scanner(System.in); n.nextLine(); } – zsubzwary Apr 29 '18 at 09:50
  • no. not immediatly – Philipp Sander Apr 30 '18 at 10:35