Home > Java > Java Tutorial > body text

In Java, how do we explicitly call garbage collection (GC)?

王林
Release: 2023-09-05 18:29:12
forward
789 people have browsed it

In Java, how do we explicitly call garbage collection (GC)?

When there are no references to an object, the object will be finalized, and when Garbage collection begins, these finalized objects will be automatically Collection, this will be done by JVM. We can call garbage collection directly, but there is no guarantee that GC will start execution immediately.

We can explicitly call garbage collection in two ways:

  • System.gc() method
  • Runtime.gc() method

java.lang.Runtime.freeMemory() method returns the free memory in Java Virtual Machine (JVM) quantity. Calling the gc() method may cause the freeMemory return value to increase.

Example

Demo

public class GarbageCollectionTest {
   public static void main(String args[]) {
      System.out.println(Runtime.getRuntime().freeMemory());
      for (int i=0; i<= 100000; i++) {
         Double d = new Double(300);
      }
      System.out.println(Runtime.getRuntime().freeMemory());
      System.gc();
      System.out.println(Runtime.getRuntime().freeMemory());
   }
}
Copy after login

Output

15648632
13273472
15970072
Copy after login

The above is the detailed content of In Java, how do we explicitly call garbage collection (GC)?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!