Memory Usage – JAVA


Rami Martin
Memory Usage – JAVA

Hello everyone,

Today I want to talk about memory. Especially about memory in JAVA. In game development, as you know, we are always looking for the best optimisation. To see in the code how your memory evolves, we’ve written some code for help.

First of all, we need to know how the memory allocation works in JAVA. For each application running on the JVM, the memory is divide by 3 blocks. You have the used memory, the free memory that can be directly used to create new object. And the unlocated memory that can be used if you need more memory during your life running.

In Java you have three methods to access of the memory data.

The free memory directly writable :

Runtime.getRuntime().freeMemory();

The total memory which not include the unlocated memory :

Runtime.getRuntime().totalMemory();

And the max memory, unlocated memory included :

Runtime.getRuntime().maxMemory();

So, with that, we can know how much memory is used, how much memory left and how much unlocated memory left for your application.

The used memory :

long totalMem = Runtime.getRuntime().totalMemory();
long freeMem = Runtime.getRuntime().freeMemory();
long usedMem = totalMem - freeMem;

The total free memory :

long maxMem = Runtime.getRuntime().maxMemory();
long totalFreeMem = maxMem - usedMem;

The unlocated memory left :

long unlocatedMem = maxMem - totalMem;

Don’t forget that the result is in bytes. So, if you want to get this value in KiloByte, MegaByte, GigaByte (in french : KiloOctet, MégaOctet, GigaOctet), you should convert it. For that, you can do it with a simple enum :

    public enum ByteUnit{
        B(1), KB(1000), MB(1000000), GB(1000000000);

        public int unit;
        ByteUnit(int unit) {
            this.unit = unit;
        }

        public long convert(long bytes){
            return bytes / unit;
        }
    }

And simply convert like that :

long maxMem = Runtime.getRuntime().maxMemory();
long maxMemInKB = ByteUnit.KB.convert(maxMem);

If you want the java class ready to use, you can find it in our git.

https://github.com/DrGamesFr/Libgdx-Tools/blob/master/MemoryUtils.java

See you for the next post. Kiss kiss.

Show Comments (0)

Comments

This site uses Akismet to reduce spam. Learn how your comment data is processed.