Week 125 — How can one set the heap size of a Java application?
Question of the Week #125
How can one set the heap size of a Java application?
2 Replies
By default, the JVM detects a suitable heap size given system and environment constraints but sometimes, developers may want to set it to a different value.
For configuring the heap site, the most important option is the maximum heap size which can be set with the
-Xmx
argument. This argument must come before the main class or the -jar
argument when calling the java
command:
Similar to the maximum heap size, it is also possible to set an initial heap size. When the application starts, it will start with that heap size and allocate more memory if necessary until it reaches the maximum heap size.
📖 Sample answer from dan1st
Why the need?
We get
OutOfMemoryError
when the heap memory runs out. When this happens the JVM throws the OutOfMemoryError and if it is uncaught the program crashes.
Check JVM heap settings
To see how your JVM chooses defaults:
You’ll see values like:
These are set ergonomically based on your machine’s specs.
Example
In this Example we keep allocating 10MB chunks of memory until we get the OutOfMemoryError
.
Solution
We can set the initial as well as the max heap size by passing some VM options when we run the program.
- -Xms
: initial heap size
- -Xmx
: max heap size
We can pass these options like this:
Or for more verbose GC info we can add this options as well
Submission from oneplusiota