When starting Java applications on the command line, I am often instructed to supply parameters such as -Xms512m
or -Xmx2g
. What are these parameters for?
The -Xms
and -Xmx
parameters are used to control the initial and maximum heap size allocated to the Java Virtual Machine (JVM). This is the amount of memory in bytes that will be used for creating and storing objects. Values for these parameters can be specified as bytes or in the following larger units:
k
for kilobytes (e.g. -Xms512k
)m
for megabytes (e.g. -Xms256m
)g
for gigabytes (e.g. -Xms1g
)The value specified in -Xms
will be allocated to the heap when the program starts. For example, -Xms256m
will allocate 256 megabytes to the heap. The heap is not a fixed size: if more memory is needed, it can grow, up to a maximum of the size specified in -Xmx
. So, for example, -Xmx1g
will set the maximum heap size to 1 gigabyte. When both of these example parameter values are used together, i.e. -Xms256m -Xmx1g
, the size of the heap will initially be 256 megabytes but will be allowed to grow to 1 gigabyte during the program’s lifecycle.
The amounts provided to each parameter will depend on the resources of the system running the application and the application’s memory requirements. It is therefore difficult to provide a generic suggestion for setting these parameters. Keep the following points in mind:
java.lang.OutOfMemoryError: Java heap space
. However, setting it too high may cause the application to interfere with other applications on the system.If -Xms
and -Xmx
are not explicitly set, the JVM will set the initial heap size based on the amount of available physical memory on the system and the maximum heap size based on the total amount of physical memory on the system. The exact details of these default settings will depend on the JVM implementation in use and whether it is in client or server mode.
Loved by over 4 million developers and more than 90,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.