Java: How much memory is allocated to this process?

advertisements

I've written a unit test which is very demanding on memory. It requires the -Xmx2048m parameter, otherwise get a OutOfMemoryException.

Is there a way to check, from within the test, how much memory is allocated? It would be useful to write a test such as TestsHaveEnoughMemory, and fail it with an explanatory error message that tells the user a memory parameter is required.


You can use the Runtime class to do that.

Try this;

long total_memory = Runtime.getRuntime().totalMemory();    // Total available now
long free_memory = Runtime.getRuntime().freeMemory();      // Free memory now
long max_memory = Runtime.getRuntime().maxMemory();        // Max available ever