How much memory is my program using Java

I created a program that uses the A * search algorithm to solve 8 puzzles. I was interested to know how much memory is used by my program from start to finish.

So far i have done

At the beginning of the program

static double totalMem = Runtime.getRuntime().totalMemory()/(1024*1024); static double memoryMax = Runtime.getRuntime().maxMemory()/(1024*1024); 

and at the end of the program

  timeTaken-=System.currentTimeMillis(); System.out.println("\n\n-------Total Time Taken = "+Math.abs(timeTaken)+ " millisec ------\n "); System.out.println("-------Maximum Memory = "+memoryMax+" MB------\n "); System.out.println("-------Total Memory = "+totalMem +" MB------\n "); currMem = Runtime.getRuntime().freeMemory()/(1024*1024); System.out.println("-------Free Memory = "+currMem+" MB------\n "); double memUsed = (Runtime.getRuntime().totalMemory())/(1024*1024)-currMem; System.out.println("-------Total Used = "+memUsed +" MB------\n "); 

This does not seem right. When I test different datasets. Any suggestive

+5
source share
4 answers

It would be better to use a profiler or similar software for this purpose. You can start with jvisualvm, which is included in the JDK or JProfiler.

+6
source

The problem is with the local thread allocation buffer.
Objects can be created on TLAB.
Read this: https://blogs.oracle.com/jonthecollector/entry/the_real_thing
Therefore, every time you run the program, it will show similar values.
Run the program by disabling this function, skip below in the VM arguments: -

 -XX:-UseTLAB 
0
source

You can also use "Java Mission Control" (a newer version of JVisualVM), which allows you to take snapshots of your memory. Add these parameters when starting your program:

 -XX:+UnlockCommercialFeatures -XX:+FlightRecorder -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=9010 -Dcom.sun.management.jmxremote.local.only=true -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false 

The bin folder of your JDK 7 is also called jmc.exe

0
source

Runtime is working correctly. You could accept the difference before executing the logic and after seeing how much memory is being used. Quick sample

 import java.util.ArrayList; import java.util.List; public class MemoryTest { private static final int KB = 1024; public static void main(String[] args) { long initialMemory = getUsedMemory(); List<String> dummy = new ArrayList<String>(); for(int i=0; i<10000; i++){ dummy.add("Dummy " + i); } System.out.println("Total used by program = " + (getUsedMemory() - initialMemory) + " KB"); } private static long getUsedMemory() { Runtime runtime = Runtime.getRuntime(); return (runtime.totalMemory() - runtime.freeMemory()) / KB; } } 
0
source

All Articles