How to Free Memory in Java

How to free memory in Java?

Java uses managed memory, so the only way you can allocate memory is by using the new operator, and the only way you can deallocate memory is by relying on the garbage collector.

This memory management whitepaper (PDF) may help explain what's going on.

You can also call System.gc() to suggest that the garbage collector run immediately. However, the Java Runtime makes the final decision, not your code.

According to the Java documentation,

Calling the gc method suggests that
the Java Virtual Machine expend effort
toward recycling unused objects in
order to make the memory they
currently occupy available for quick
reuse. When control returns from the
method call, the Java Virtual Machine
has made a best effort to reclaim
space from all discarded objects.

Total free memory java

This is because JVM created int[] ar in TLAB (thread-local allocation buffer).Let me explain this with the following example:

1) Suppose total memory in the system was 100 units.

2) The current thread has already created a TLAB beofre even a single line of code has run.

3) TLAB's memory(say 10 units) is already deducted from the total memory i.e (Runtime.freeMemory shows 90 units)

4) int[] ar is created inside TLAB as TLAB has free space.

5) After creating of int[] ar running Runtime.freeMemory showed 90 units ( as it is created inside the TLAB).

6) Now on doing GC you get to see 100 units again



Related Topics



Leave a reply



Submit