Reputation: 1197
Below code prints the same value for the memory? Ideally after object allocation free memory should be reduced. Is my understanding correct?
System.out.println(Runtime.getRuntime().freeMemory());
Person p = new Person();
p.setFirstName("bob");
System.out.println(Runtime.getRuntime().freeMemory());
Upvotes: 2
Views: 793
Reputation: 135992
This is because JVM created Person in TLAB (thread-local allocation buffer), you can find short explanation in Peter Lawrey's comment and more detail from one of HotSpot developers here https://blogs.oracle.com/daviddetlefs/entry/tlab_sizing_an_annoying_little. What actually happening is as follows:
Before you ran the first Runtime.freeMemory
the current thread had already created a TLAB in heap and Runtime.freeMemory
showed free memory without TLAB. When you created a Person it was placed in TLAB because TLAB had free space in it, so from the point of view of Runtime.freeMemory
nothing changed.
Try to turn off this feature when running the test
java -XX:-UseTLAB ...
and it will show the correct Person's size
Upvotes: 2
Reputation: 12027
Please go through the official documentation for free memory and total memory
Free Memory:
public long freeMemory()
: Returns the amount of free memory in the Java Virtual Machine. Calling the gc method may result in increasing the value returned by freeMemory.
Returns: an approximation to the total amount of memory currently available for future allocated objects, measured in bytes.
Total Memory:
public long totalMemory()
Returns the total amount of memory in the Java virtual machine. The value returned by this method may vary over time, depending on the host environment.
Note that the amount of memory required to hold an object of any given type may be implementation-dependent.
Returns: the total amount of memory currently available for current and future objects, measured in bytes.
If you want to find out the memory used by your Object, then you have to calculate by subtracting totalMemory - freeMemory as i shown below.
System.out.prinltn("Memory Used by the Person Object" +
Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
Upvotes: 1
Reputation: 5213
As the Runtime javadoc states, freeMemory() returns an approximation to the total amount of memory currently available for future allocated objects, meaning you cannot expect a precise value.
Upvotes: 3