I have been looking in google for a solution to my problem but no success.
I have a “near real-time” application that checks available memory from time to time and notifies the user in case there is no less than 10% free memory in the system.
I am using the following code to do so:
double free = Runtime.getRuntime().freeMemory();
double total = Runtime.getRuntime().maxMemory();
double freeMemoryProc = (free / total) * 100;
if (freeMemoryProc <= 10) {
// Warn user...
}
This bit of code is working fine most of the time but is giving me erroneous messages when the GC did not kick in time to collect all unused memory.
Questions:
-
Am I right when saying that
freeMemoryProcis not a true measurement as it depends on when the GC kicks in? -
Is there a better way (preferably independent from GC) to calculate the amount of available memory for a my application?
Related question (did not help)
Obtaining memory available to JVM at runtime
Thanks in advance,
Regards.
Yes … sort of. It is a measure of the amount of memory that is not currently allocated, not of memory that could be allocated if necessary.
There is no way to do this that is independent of the garbage collector. In general, the only way that you can tell if memory that is currently allocated to objects is “in use” in the sense that it is not uncollected garbage is … to run the garbage collector.
The best you can do is to capture the memory usage immediately after a garbage collector run, and hope that the pattern of memory usage is relatively smooth.
Note that running the GC simply to find out how much memory is left is a bad idea from a performance perspective … and especially in a near real-time application. (But I guess you already know that!)