Runtime.Freememory () returns the value of a variable between two consecutive calls when the array is initialized between them?

Why am I getting variable output for the following code:

Runtime rt = Runtime.getRuntime(); long x,y; x = rt.freeMemory(); char z[] = new char[Index]; y = rt.freeMemory(); System.out.println("Difference = " + (xy)) 

Output = zero for a lower index value (<10000), but for values> = 100000 the value is 200016. For each addition of zero, it is 2000016.

How is this possible. [edit] My goal is to find the size of the data object (used in the code, as here, I used Char z [] the size of the index) in memory.

+4
source share
2 answers

Your guess is that if you have n bytes of free memory and m bytes are allocated, then you will have nm bytes of free memory.

This is a rational hypothesis, but it is false in the presence of asynchronous garbage collectors, which will or will not do jsut memory compression on their own.

And even if you spent years studying the behavior of a particular JVM and accumulated deep wisdom and knowledge that allowed you to predict the effect of distribution on the result of freeMemory (), this knowledge may suddenly become useless when switching to another JVM or just update the current one.

Therefore, trust us elders and see Runtime.freeMemory() as a kind of fun random number generator.

+2
source

I am writing System.gc() , and you can see the difference.

  Runtime rt = Runtime.getRuntime(); long x,y; System.gc(); x = rt.freeMemory(); char z[] = new char[1000]; y = rt.freeMemory(); System.out.println("X = " + (x)); System.out.println("Y = " + (y)); System.out.println("Difference = " + (xy)); 

Exit

 X = 16179672 Y = 16085904 Difference = 93768 
0
source

Source: https://habr.com/ru/post/1411362/


All Articles