java: how do I know how much memory a program uses?


There is a task: to write a small program that runs from the command line, reads data from a file, calculates the result (the area of the shape) and writes it to another file.

One of the conditions is:

The amount of memory used should not exceed 16 MB.

Please tell me how you can determine how much memory the program uses?

Windows, IntelliJIdea.

Author: Miller777, 2015-08-29

1 answers

The simplest thing is like this:

long usedBytes = Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory();

The result is in bytes (divide by 1048576 to get megabytes). Most likely, the task implies that at no time is more than 16Mb used. You can simply run the program with the -Xmx16M parameter, which will limit the maximum volume:

java -Xmx16M MyClass

Now, if you do not meet the volume, the program will simply crash with the exception OutOfMemoryError. In the program code itself, you do not need to check anything further.

 5
Author: Tagir Valeev, 2015-08-29 03:06:18