That solution is a bad idea. Any other processes running in the JVM may fail to allocate memory (because this code grabbed it all) and that is likely to cause problems.
System performance may be impaired because processes start disk swapping. Depending on how the JVM works it may do a lot of work to initialise memory that you never access.
You might try:
Runtime.getRuntime().freeMemory()
Runtime.getRuntime().maxMemory()
Runtime.getRuntime().totalMemory()
Refer to the documentation for the limitations of what they return.
Also remember that while you can obtain these values in bytes the size of Java objects is implementation defined and remains obscure.
If you're planning to use this you might also need Instrumentation.getObjectSize()
to understand the approximate size of objects. Accessing instrumentation is frankly more trouble than it should be. Here's an answer about how to: In Java, what is the best way to determine the size of an object?
All of these values are guidelines only. They may make sense in a caching strategy in which you want to tune how much space is allocated to a discardable cache but not as exact values for any purpose.