How to force garbage collection in Java?

后端 未结 22 1408
离开以前
离开以前 2020-11-22 00:31

Is it possible to force garbage collection in Java, even if it is tricky to do? I know about System.gc(); and Runtime.gc(); but they only suggest t

相关标签:
22条回答
  • 2020-11-22 01:10

    On OracleJDK 10 with G1 GC, a single call to System.gc() will cause GC to clean up the Old Collection. I am not sure if GC runs immediately. However, GC will not clean up the Young Collection even if System.gc() is called many times in a loop. To get GC to clean up the Young Collection, you must allocate in a loop (e.g. new byte[1024]) without calling System.gc(). Calling System.gc() for some reason prevents GC from cleaning up the Young Collection.

    0 讨论(0)
  • 2020-11-22 01:12

    It would be better if you would describe the reason why you need garbage collection. If you are using SWT, you can dispose resources such as Image and Font to free memory. For instance:

    Image img = new Image(Display.getDefault(), 16, 16);
    img.dispose();
    

    There are also tools to determine undisposed resources.

    0 讨论(0)
  • 2020-11-22 01:14

    Under the documentation for OutOfMemoryError it declares that it will not be thrown unless the VM has failed to reclaim memory following a full garbage collection. So if you keep allocating memory until you get the error, you will have already forced a full garbage collection.

    Presumably the question you really wanted to ask was "how can I reclaim the memory I think I should be reclaiming by garbage collection?"

    0 讨论(0)
  • 2020-11-22 01:14

    JVM specification doesn't say anything specific about garbage collection. Due to this, vendors are free to implement GC in their way.

    So this vagueness causes uncertainty in garbage collection behavior. You should check your JVM details to know about the garbage collection approaches/algorithms. Also there are options to customize behavior as well.

    0 讨论(0)
提交回复
热议问题