2

I am testing memory consumption of a block of code by using:

long totalMemory = Runtime.getRuntime().totalMemory();
long freeMemory = Runtime.getRuntime().freeMemory();

Used memory is the difference between totalMemory and freeMemory. I launched and run the same program three times with exactly same conditions. But the used memory amount differs a lot:

1120M
802M
312M

What might cause this? And should I take the average of the three as the memory usage of the code? First time doing this, and thanks for any insights on this.

6
  • According to the Java Runtime Library: "The value returned by totalMemory method may vary over time, depending on the host environment." Commented Apr 1, 2014 at 18:34
  • I ran immediately after another run, and nothing has changed. Commented Apr 1, 2014 at 18:36
  • So, do you run each program on the same jvm, or are you invoking each program with its own jvm? Commented Apr 1, 2014 at 18:38
  • I'm sure garbage collection has something to do with it. It's going to be hard to know for sure unless you profile your code with an actual tool (such as jvisualvm or jconsole). Commented Apr 1, 2014 at 18:39
  • I run it in Eclipe, so with same JVM each time. Commented Apr 1, 2014 at 18:43

1 Answer 1

1

This is couse due to java java vitual machine (JVM). Java use three types of memmory structures.

  1. Heap memmory
  2. Non heap memmory
  3. other memmory

So Garbage collector also run in JVM. That also effect to change memmory usage. You can reffer this link to more details.

http://www.yourkit.com/docs/kb/sizes.jsp

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.