Other answers provide a runtime mechanism through Runtime.getRuntime (). totalMemory () and maxMemory (), but VERY careful - the answer will be correct only at the moment. After the GC, totalMemory () will change (down!). You cannot have an absolutely accurate idea of βββhow many living objects exist in the systemβ always, since this is exactly what the GC calculates and is expensive.
Using JMX (see GC bean, etc.) will help with this survey, but again, this is a pattern over time.
So, I'm not sure what you are actually trying to solve here ...
source share