Java Programming 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.
		freeJVMMemory = runtime.freeMemory();
		System.out.println("JVM Free Memory After Garbage Collection: " +freeJVMMemory);
$ javac
$ 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   
        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                                                    
        // After deallocation free memory size
        System.out.println("Free memory after deallocation: " + runtime.freeMemory());
$ 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 Programming 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 Programming Gets Current Date

Java Programming Finds Character Vowel or Consonent

Java Programming HCF and LCM Computation

Java Programming Sum of Command Line Integer Arguments

Java Programming Multiplication of Command Line Integer Arguments

Java Programming Multiplication of Command Line Floating Point Numeric Arguments

Java Programming String Contains or Not

Java Programming Gets Grade Description using Switch

Java Programming CSV File Reader

Java Programming Character Frequency Count in String using for each

Java Programming Finds Min from Integer Array by Passing Array to Method

Java Programming Linear Search

Java Programming Binary Search

Java Programming Ternary Search

Java Programming Generates Range of Numbers

Java Programming Generates Range of Characters

Java Programming Computes Square Root Value

Java Programming Checks Number is Positive or Negative

Java Programming Checks Number is Odd or Even

Java Programming Computes Plot Area

Java Programming Convert Number of Days into Years

Java Programming Checks a Year is Leap Year, Century Year or Not

Java Programming Checks a Character is Digit, Letter or neither digit nor letter

Java Programming Checks a Number is Palindrome or not

Java Programming Sum of Two Matrix

Java Programming Power Computation

Java Programming Checks Number is an Armstrong Number or not

Java Programming Temperature Unit Conversions

Java Programming Generates Random Numbers in Specified Range

Java Programming Computes Sum of Digits and Product of Digits

Java Programming Computes Reverse Number

Java Programming Computes Factorial Value

Java Programming Checks Prime Number or not

Java Programming Computes Harmonic Series

Java Programming Generates Floyd's Triangle

Java Programming Reverses String

Java Programming Checks Palindrome String or not

Java Programming Opens Notepad

Java Programming Searches String using RegEx Pattern

Java Programming Searches Word in String

Java Programming Gets System Environment Variables

Java Programming Gets IP Address of Server Name

Java Programming Arrays Sort and Reverse using sort method

Java Programming Bubble Sorting

Java Programming Selection Sorting

Java Programming Insertion Sorting

Java Programming Merge Sorting

Java Programming Quick Sorting

Java Programming Counting Sort

Java Programming Radix Sorting

Java Programming Sorting Array of Strings

Java Programming String Characters Sorting

Java Programming Sum of First N Numbers

Java Programming Product of First N Numbers

Privacy Policy  |  Copyright@2017 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Free online programming tutorials

Email Facebook Google LinkedIn Twitter