Reputation: 8136
Why I am getting a 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 = " + (x-y))
Output is = Zero for lesser Value of Index(<10000) but for values >=100000 value is 200016.For every Zero addition it becomes 2000016.
How is it possible. [edited]My aim is to find the size of the Data Object(used in the code- like here I have used Char z[] of Index Size) in the memory.
Upvotes: 4
Views: 237
Reputation: 36329
Your assumption seems to be that if you have n bytes of free memory, and allocate m bytes, then you will have n-m bytes of free memory afterwards.
This is a rational hypothesis, but it is false in the presence of asynchronous garbage collectors that will or will not do memory compaction jsut as they see fit.
And even if you spend years to study the behaviour of a certain JVM and accumulated deep wisdom and knowledge that allowed you to predict the effect of allocation on the result of freeMemory(), this knowledge may suddenly become worthless as you switch to another JVM or only update your current one.
Hence, trust us elder ones and look at Runtime.freeMemory()
as a kind of a funny random number generator.
Upvotes: 2
Reputation: 6657
I write 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 = " + (x-y));
Output
X = 16179672
Y = 16085904
Difference = 93768
Upvotes: 0