If you are new in kotlin or JVM based system and want to know how to get free memory, total memory and max memory from the runtime class, here's I have shared some example to answer some beginners question.

Let's start with understanding whats the difference between each of them:

Differences between these memory options

  • freeMemory is currently available memory which can be allocated to future objects
  • totalMemory  is the total amount of memory reserved for the java process
  • maxMemory equals to initial heap size, configured by -Xmx value

How to get free memory in Kotlin

Get currently free memory available for creating object. Caution: this is not the total free available memory


How to get total memory in Kotlin

Used memory currently occupied by existing objects + free memory available for new objects.


How to get used memory in Kotlin

It can be calculated from totalMemory and freeMemory

usedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();

Converting size in MegaBytes

Each of the memory function returns size in bytes. Then we convert in MB by dividing with 1024*1024

Output for the given kotlin example

Total memory: 256MB
Free memory: 253MB
Used memory: 3MB
Max memory: 4096MB