Java garbage collection

前端 未结 7 2127
生来不讨喜
生来不讨喜 2020-12-05 09:44

Java automatically calls garbage collector, then why we need manual calls for garbage collection? When should use System.gc()

7条回答
  •  萌比男神i
    2020-12-05 10:05

    System.gc() is only a suggestion. But it does make sense in some situations.

    Suppose you have class MyClass, and you're wondering how much memory does one instance take. What you can do is this (roughly speaking):

    MyClass [] objects= new MyClass[100000];
    System.gc();
    long memoryNow = Runtime.getRuntime().freeMemory();
    for (int i = 0; i < 100000; i ++) {
      objects[i] = new MyClass();
    }
    System.gc();
    long memoryLater = Runtime.getRuntime().freeMemory();
    int objectSize = (int)((memoryLater - memoryNow) / 100000);
    

    There are other similar cases I've found System.gc() to be useful.

提交回复
热议问题