Java- Example of Memory management

//Example of Memory management using 3 functions

//totalmemory():: gives total  heap size
//freememory()::gives now  available heap memory
// gc():: by force calling garbage collector(ie before jvm time slice).


class MemoryDemo
{


public static void main(String ar[])
{

Runtime r=Runtime.getRuntime();

System.out.println("Total Heap Memory="+r.totalMemory());

long mem1;//mem1 store initial free memory

mem1=r.freeMemory();


System.out.println("Initial Free Heap Memory="+mem1);


r.gc();//calling garbage collector by force

mem1=r.freeMemory();

System.out.println(" Free Heap Memory after calling garbage collector="+mem1);




//memory allocation

Integer a[]=new Integer[1000];

for(int i=0;i<1000;i++)
{

a[i]=i;

}


long mem2;// To store free memory after memory allocation


mem2=r.freeMemory();
System.out.println(" Free Heap Memory after memory allocation="+mem2);
System.out.println(" Memory used by 1000 integers ="+(mem1-mem2));


//Memory deallocation

for(int i=0;i<1000;i++)
{

a[i]=null;

}


mem2=r.freeMemory();
System.out.println(" Free Heap Memory after memory deallocation without calling gc="+mem2);

r.gc();

long mem3=r.freeMemory();
System.out.println(" Free Heap Memory after memory deallocation after  calling gc="+mem3);

System.out.println(" Memory Released ="+(mem3-mem2));

}


}

Reactions: