Although Java provides automatic garbage collection, sometimes you wonder how big the object heap is and how much is left. This information can be used to check the efficiency of the code and to check approximately how many objects of a particular type can be instantiated. To obtain these values, we use total memory() and free memory methods.
As we all know that, Java's garbage collector runs periodically to reclaim unused objects. We can call the garbage collector on demand by calling the gc() method. A good attempt is to call gc() and then free memory().
Methods:
Syntax:
public void gc() Returns: NA. Exception: NA.
Syntax:
public long freeMemory() Returns: an approximation to the total amount of memory currently available for future allocated objects, measured in bytes. Exception: NA.
Syntax:
public long totalMemory() Returns: the total amount of memory currently available for current and future objects, measured in bytes. Exception: NA.
// Java code illustrating gc(), freeMemory() // and totalMemory() methods class memoryDemo { public static void main(String arg[]) { Runtime gfg = Runtime.getRuntime(); long memory1, memory2; Integer integer[] = new Integer[1000]; // checking the total memory System.out.println("Total memory is: " + gfg.totalMemory()); // checking free memory memory1 = gfg.freeMemory(); System.out.println("Initial free memory: " + memory1); // calling the garbage collector on demand gfg.gc(); memory1 = gfg.freeMemory(); System.out.println("Free memory after garbage " + "collection: " + memory1); // allocating integers for (int i = 0; i < 1000; i++) integer[i] = new Integer(i); memory2 = gfg.freeMemory(); System.out.println("Free memory after allocation: " + memory2); System.out.println("Memory used by allocation: " + (memory1 - memory2)); // discard integers for (int i = 0; i < 1000; i++) integer[i] = null; gfg.gc(); memory2 = gfg.freeMemory(); System.out.println("Free memory after " + "collecting discarded Integers: " + memory2); } }
Output:
Total memory is: 128974848 Initial free memory: 126929976 Free memory after garbage collection: 128632384 Free memory after allocation: 127950744 Memory used by allocation: 681640 Free memory after collecting discarded Integers: 128643696