Coders Packet

Memory Management in Java

By Dendi Keerthi

This Memory Management in Java is useful to know about how much memory is being used and how much memory is free after all the uses, allocations, and garbage collection.

Implementation of Memory Management 

Memory Management is one of the common uses of the Runtime class. Although Java provides automatic garbage collection sometimes it is necessary to know how large the object heap is and how much of it is left. This information can be used to check the code for efficiency or know how many more objects of a certain type can be instantiated. 

We use two methods to obtain these values.

-> totalMemory()

-> freeMemory()

Objects such as Integers are allocated after garbage collection and discarded later.

Sometimes we require to collect the discarded objects prior to the garbage collector's next round. 


The following program gives detailed information regarding Memory Management.


class MemManage {
public static void main(String args[]) {
Runtime rt = Runtime.getRuntime();
long a1, a2;
Integer randomint[] = new Integer[1000];
System.out.println("Total memory available: " + rt.totalMemory());

a1 = rt.freeMemory();
System.out.println("Initial free memory available: " + a1);
a1 = rt.freeMemory();
System.out.println("Free memory available after garbage collection: " + a1);

for(int i = 0; i < 1000; i++)
randomint[i] = new Integer(i);

a2 = rt.freeMemory();
System.out.println("Free memory available after allocation: " + a2);
System.out.println("Memory utilized for allocation: " + (a1-a2));

for(int i = 0; i < 1000; i++) randomint[i] = null;
a2 = rt.freeMemory();
System.out.println("Free memory available after collecting the discarded Integers: " + a2);




Runtime.getRuntime() is a static method that is called to get the reference to the current Runtime object.

a1 and a2 are memory locations where the values of memory are stored.

totalMemory() method is used to obtain the total number of bytes of memory available.

freeMemory() method is used to obtain the number of bytes of free memory available.

gc() method is used to run the garbage collector.

The garbage collector runs automatically to recycle the unused objects periodically. We can also run a garbage collector on demand by calling the gc()method.

It is better to call gc() method first and then call the freeMemory() method to get a baseline memory usage and then again call the freeMemory() to see how much memory it is allocating.

The values of memory may vary for every other program.

Thank You


Download Complete Code


No comments yet