Java Memory Management

How memory is managed in java?

Java supports automatic garbage collection, Java's garbage collector runs in frequently to recycle or clean up unused objects.

Java also provides the provision to run garbage collector on demand by invoking gc method which is available in Runtime object.

Sometimes we may want to know how much object size in heap and how much size left in heap etc. Java has totalMemory and freeMemory methods to get these information.

Memory management supports to check code for efficiency or how many objects of certain type can be instantiated etc.

Java Programming Performs Garbage Collection

This simple java program illustrates to trigger the garbage collection manually.

freeMemory method in Runtime class is used to get the available memory size in JVM (Java Virtual MAchine).

gc method is used to perform the garbage collection.

import java.util.*;

public class GarbageCollectionTest {
	public static void main(String[] args){
		Runtime runtime = Runtime.getRuntime();
		long freeJVMMemory = runtime.freeMemory();
		System.out.println("JVM Free Memory Before Garbage Collection: " +freeJVMMemory);
		// Performs garbage collection.
		runtime.gc();
		freeJVMMemory = runtime.freeMemory();
		System.out.println("JVM Free Memory After Garbage Collection: " +freeJVMMemory);
	}
}
Output:
$ javac GarbageCollectionTest.java
$ java GarbageCollectionTest 
JVM Free Memory Before Garbage Collection: 125535480
JVM Free Memory After Garbage Collection: 126594096

How to do clean up unused objects in java manually?

gc() method is available in Runtime object to manually recycle or clean up unused objects in java.

Java program with running garbage collection on demand

import java.util.*;                                                             
class MemoryManagement {                                                        
    public static void main(String args[]) {                                    
        Runtime runtime = Runtime.getRuntime();                                 
        Integer integerList[] = new Integer[2000];    
        // Getting total memory in heap on machine                          
        System.out.println("Total Memory: " + runtime.totalMemory());  
        // Getting free memory in heap on machine         
        System.out.println("Initial Free Memory: " + runtime.freeMemory());  
        // Manually running garbage collector   
        runtime.gc();                                                           
        long memoryBefore = runtime.freeMemory();                               
        System.out.println("Free memory after Garbage Collection: " + memoryBefore);
        Random random = new Random();    
        // Alocating memory for each integer elements in array                                       
        for(int i =0; i<2000; i++) {                         
            //Generates random integer number for each array elements                   
            integerList[i] = new Integer(random.nextInt());                     
        }                              
        // Gets free memory after array elements allocation
        long memoryAfter  = runtime.freeMemory();                               
        System.out.println("Free memory after allocation:  " + memoryAfter);  
        // Difference to get allocation size before and after allocated for integer array elements.  
        System.out.println("Memory is used for allocation:  " + (memoryBefore-memoryAfter));
        // Deallocating array elements
        for(int i =0; i<2000; i++) {                                            
            integerList[i] = null;                                              
        }                                                                       
        //Garbage collection                                                    
        runtime.gc();                 
        // After deallocation free memory size
        System.out.println("Free memory after deallocation: " + runtime.freeMemory());
    }                                                                           
}  
Output:
$ java MemoryManagement
Total Memory: 247463936
Initial Free Memory: 246163688
Free memory after Garbage Collection: 247194624
Free memory after allocation:  245894320
Memory is used for allocation:  1300304
Free memory after deallocation: 245891576

What is finalize method in java?

Sometimes object may need to perform some action when it's destroyed. suppose object is holding some non java resource such as a file handle or window character font, so object might ensure these resources are freed before object is destroyed.
Java provides finalize method to handle some action before an object is destroyed.
protected void finalize() {
//code to release resources which object holds.
}
finalize() method will be invoke when an object is just about to be destroyed by garbage collector in java.
Java Examples

GCD and Rational Number Java Program

Java Queue Program using exception

Java Stack Program using exception

Addition of three integers java program

Biggest of three integers java program

Fibonacci numbers java program

Arithmetic Operations Menu java program

Second Smallest Element In Array Java Program

Transpose Of A Matrix Java Program

Java Program to Display triangle of stars (*)

Java Programming Prints Product Tables

Java Program to Display triangle of numbers

Java Program to Get Current Date

Java Program to Find Character Vowel or Consonent

Java Program to Compute HCF and LCM

Java Program to Sum the Command Line Integer Arguments

Java Programm to Multiply the Command Line Integer Arguments

Java Program to Find Multiplication of Command Line Floating Point Numeric Arguments

Java Program to Check String Contains or Not

Java Program to Get Grade Description using Switch

Java Program for CSV File Reader

Java Program to Find Character Frequency Count in String using for each

Java Program to Find Min from Integer Array by Passing Array to Method

Java Program Linear Search

Binary Search Java Program

Ternary Search Java Program

Java Program to Generate Range of Numbers

Java Program to Generate Range of Characters

Java Program to Compute Square Root Value

Java Program to Check Number is Positive or Negative

Java Program to Check Number is Odd or Even

Java Program to Compute Plot Area

Java Program to Convert Number of Days into Years

Java Program to Check a Year is Leap Year, Century Year or Not

Java Program to Check a Character is Digit, Letter or neither digit nor letter

Java Program to Check a Number is Palindrome or not

Java Program to Sum Two Matrix

Java Program to Compute Power

Java Program to Check Number is an Armstrong Number or not

Java Program for Temperature Unit Conversions

Java Program to Generate Random Numbers in Specified Range

Java Program to Compute Sum of Digits and Product of Digits

Java Program to Compute Reverse Number

Java Programming Computes Factorial Value

Java Programming Checks Prime Number or not

Java Program to Compute Harmonic Series

Java Program Generate Floyd's Triangle

Java Program to Reverse String

Java Program to Check Palindrome String or not

Java Program to Open Notepad

Java Program to Search String using RegEx Pattern

Java Program to Search Word in String

Java Program to Get System Environment Variables

Java Program to Get IP Address of Server Name

Java Program for Arrays Sorting and Reverse using sort method

Java Program for Bubble Sorting

Java Program for Selection Sorting

Java Program for Insertion Sorting

Java Program for Merge Sorting

Java Program for Quick Sorting

Java Program for Counting Sort

Java Program for Radix Sorting

Java Program for Sorting Array of Strings

Java Program for String Characters Sorting

Java Program to Sum First N Numbers

Java Program to Product First N Numbers

Java Program to get URL details

Java Program to get URL HTML Content

Java Program to get URL details

Java Program to get URL HTML Content

Privacy Policy  |  Copyrightcopyright symbol2020 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Email Facebook Google LinkedIn Twitter
^