Is there any good way to get the remaining memory available to the JVM at run time? The use case of this would be to have web services which fail gracefully when they are nearing their memory limits by refusing new connections with a nice error message "too many people using this, try again later", rather than dying abruptly with an OutOfMemory error.
Note this has nothing to do with calculating/estimating the cost of each object beforehand. In principle I could estimate how much memory my objects take and refuse new connections based on that estimate, but that seems kind of hacky/fragile.
This sample by William Brendel may be of some use.
EDIT: I originally provided this sample (linking to William Brendel's answer on another topic). The creator of that topic (Steve M) wanted to create a multi-platform Java application. Specifically, the user was trying to find a means by which to assess the running machine's resources (disk space, CPU and memory usage).
This is an inline transcript of the answer given in that topic. However, it has been pointed out on this topic that it is not the ideal solution, despite my answer being marked as accepted.
User Christian Fries points out that it is wrong to assume that
Runtime.getRuntime().freeMemory()
gives you the amount of memory which may be allocated until an out-of-memory error occurs.From the documentation, the signature return of
Runtime.getRuntime().freeMemory()
is as such:Returns: an approximation to the total amount of memory currently available for future allocated objects, measured in bytes.
However, user Christian Fries claims this function may be misinterpreted. He claims that the approximate amount of memory which may be allocated until an out-of-memory error occurs (the free memory) is likely to be given by:
With
allocatedMemory
being given by:The key here is a discrepancy between the concept of free memory. One thing is the memory that the operating system provides the Java Virtual Machine. Another is the total amount of bytes comprising the chunks of blocks of memory actually being used by the Java Virtual Machine itself.
Considering that memory given to Java applications is managed in blocks by the Java Virtual Machine, the amount of free memory available to the Java Virtual Machine may not exactly match the memory available for a Java application.
Specifically, Christian Fries denotes the usage of the
-mx
or-Xmx
flags to set the maximum amount of memory available to the Java Virtual Machine. He notes the following function differences:Christian concludes his answer by stating that
Runtime.getRuntime().freeMemory()
in fact returns what may be called presumable free memory; even if a future memory allocation does not exceed the value returned by that function, if the Java Virtual Machine has not yet received the actual chunk of memory assigned by the host system, ajava.lang.OutOfMemoryError
may still be produced.In the end, the proper method to use will have a varying degree of dependence on the specifics of your application.
I provide another link which may be useful. It is a question made by user Richard Dormand and answered by stones333 about determining the default Java heap size used.
Note: All the answers so far, even the accepted one, seem to answer the question by saying that
Runtime.getRuntime().freeMemory()
gives you the amount of memory which may be allocated until an out-of-memory error occurs. However: this is wrong.The approximate amount of memory which may be allocated until an out-of-memory error occurs, i.e., the free memory is likely
where
Explanation: If you launch the JVM via an -mx parameter (or -Xmx) you specify the maximum amount available to the JVM.
Runtime.getRuntime().maxMemory()
will give you this amount. From this amount of system memory the JVM will allocate memory in chunks, say for example blocks of 64 mb. At start, the JVM will only allocate such a chunk from the system and not the full amount.Runtime.getRuntime().totalMemory()
gives the total memory allocated from the system, whileRuntime.getRuntime().freeMemory()
gives you the free memory within the total memory allocated.Hence:
is the free memory already reserved by the JVM, but it is likely just a small amount. And you will likely get
presumableFreeMemory
. Of course, you may get an out-of-memory exception even if you tried to allocate an amount smaller thanpresumableFreeMemory
. This may happen if the JVM does not get the next memory chunk from the system. However, on most systems this will never happen and the system will rather start swapping - a situation you like to avoid. W.r.t. to the original question: if -mx is set to a reasonable value, thenpresumableFreeMemory
is a good indicator for the free memory.To get the OS-wide available memory, add
OSHI
by using the following maven dependency:Then in Java, use the following code:
Runtime.getRuntime().freeMemory()
is a way to get free memory for JVM at that moment while runtime. Is it good way (or) not it depends completely on your application.In addition to the other answer, I would like to note that doing that is not necessarily a good idea, since you might have a cache in your app that uses SoftReferences.
Such a cache would release memory as soon as the JVM reaches its memory limits. Allocating memory, even if there's not enough free memory, would first cause memory to be released by the soft references, and make it available for the allocation.