java.util is a package library in Java that provides a set of utility classes and interfaces to work with different data types, collections, and other objects. One of the useful classes in java.util is System, which provides access to system properties and resources, as well as several methods to control the behavior of the JVM. One of those methods is System.gc(), which is used to request the JVM to run the garbage collector to free up unused memory.
Here are some examples of using System.gc() in Java:
Example 1:
// Request the JVM to run the garbage collector System.gc();
// Wait for a second to allow the garbage collector to complete Thread.sleep(1000);
// Check the total amount of memory used by the JVM long usedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); System.out.println("Used memory after GC: " + usedMemory);
In this example, we call System.gc() to request the JVM to run the garbage collector, then we wait for a second to allow the garbage collector to do its work. Finally, we check the total amount of memory used by the JVM before and after running the garbage collector.
Example 2:
public class MyClass {
// ...
public void finalize() { System.out.println("Object destroyed by the garbage collector"); } }
// Create an object of MyClass MyClass obj = new MyClass();
// Set obj to null to make it eligible for garbage collection obj = null;
// Request the JVM to run the garbage collector System.gc();
In this example, we create an object of MyClass and set it to null to make it eligible for garbage collection. When the garbage collector runs, it calls the finalize() method of the object, which simply prints a message to the console. Note that the finalize() method is called only once, after the object is destroyed by the garbage collector.
Overall, java.util System gc belongs to the java.util package library in Java. It is a useful method to control the memory usage of a Java program and free up unused objects.
Java System.gc - 30 examples found. These are the top rated real world Java examples of java.util.System.gc extracted from open source projects. You can rate examples to help us improve the quality of examples.