How to find max memory, free memory and total memory in Java?
Although Java provides automatic garbage collection, sometimes you will want to know how large the object heap is and how much of it is left. This information can be used to check the efficiency of code and to check approximately how many more objects of a certain type can be instantiated. To obtain these values, we use the
totalMemory() and freeMemory methods.
As we know Java’s garbage collector runs periodically to recycle unused objects. We can call garbage collector on demand by calling the gc() method. A good thing to try is to call gc() and then call freeMemory().
- void gc(): Runs the garbage collector. Calling this method suggests that the Java virtual machine expand effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the virtual machine has made its best effort to recycle all discarded objects.
public void gc() Returns: NA. Exception: NA.
- long freeMemory(): This method returns the amount of free memory in the Java Virtual Machine. Calling the gc method may result in increasing the value returned by freeMemory.
public long freeMemory() Returns: an approximation to the total amount of memory currently available for future allocated objects, measured in bytes. Exception: NA.
- long totalMemory(): This method returns the total amount of memory in the Java virtual machine. The value returned by this method may vary over time, depending on the host environment.
public long totalMemory() Returns: the total amount of memory currently available for current and future objects, measured in bytes. Exception: NA.
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
This article is contributed by Abhishek Verma(maverick). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.