![]() |
VOOZH | about |
In the Runtime class of Java, the maxMemory() Method returns the maximum memory designed for the Java Virtual Machine (JVM). In other words, we can say that it returns the maximum amount of memory JVM can use. This method returns a 'long' value representing the maximum amount of memory JVM can use. We can use the maxMemory() method to make runtime decisions based on available memory. It generally returns the value in bytes. If our program tries to allocate more memory than the value returned by maxMemory(), it will throw an OutOfMemoryError. In this article we are deep-diving into the use cases of the maxMemory() method with proper code demonstration.
Runtime.getRuntime().maxMemory();
We will discuss a few code snippets that demonstrate the usage of the Runtime maxMemory method. We are also going to see some of its use cases.
Below is the implementation of the above method:
This is a Simple Java Code..... Available Memory in Bytes: 259522560 Available Memory in Kilo bytes(KB): 253440 Available Memory in Mega bytes(MB): 247
In the above program, We can clearly see the method maxMemory() returns the maximum available memory Java Virtual Machine (JVM) . It return the value in Bytes. This code provides a way to check and display the available memory in different units (bytes, KB, MB) within the JVM. We can further do same for other units too.
1 KB = 1024 bytes
1 MB = 1024 KB
Below is the implementation of the above method:
System Memory Before assigning array of 10 elements Used Memory : 0 MB Total Free Memory : 246 MB System Memory Before assigning array of 10 elements Used Memory : 1 MB Total Free Memory : 246 MB
The above code is used to analyze memory usage. In arrayAssign method an integer array is initialized with 10 elements from 0 to 9. In memory method we display memory related information such as used memory and total free memory in JVM. In memory function function we have used freeMemory() , totalMemory() and maxMemory() methods to demonstrate memory related information. We have invoked memory method , arrayAssign method and again memory method to show the usage of memory by our program.
In this article, we have tried to cover all basic and intermediate implementation related to maxMemory() Method with proper and brief examples. Java Runtime maxMemory() Method return the maximum memory designed to the Java Virtual Machine (JVM). We have seen how can see our Java Virtual Machine (JVM) memory usage. This will further allows to make decision on memory optimization. We have seen two examples with clear explanation of the same. We have seen two main properties of maxMemory() method such as :
In short maxMemory() Methods used to obtain the maximum heap memory available to the JVM.