0
0
JavaHow-ToBeginner · 3 min read

How to Increase Heap Size in Java: Simple Steps

To increase heap size in Java, use the JVM options -Xms to set the initial heap size and -Xmx to set the maximum heap size when running your Java program. For example, java -Xms512m -Xmx1024m YourProgram sets the initial heap to 512 MB and max heap to 1024 MB.
📐

Syntax

The heap size in Java is controlled by two main JVM options:

  • -Xms<size>: Sets the initial heap size when the JVM starts.
  • -Xmx<size>: Sets the maximum heap size the JVM can use.

Sizes can be specified in bytes (default), or with suffixes like k (kilobytes), m (megabytes), or g (gigabytes).

bash
java -Xms512m -Xmx1024m YourProgram
💻

Example

This example shows how to run a simple Java program with increased heap size. It sets the initial heap to 256 MB and the maximum heap to 512 MB.

java
public class HeapSizeExample {
    public static void main(String[] args) {
        // Print current max heap size in MB
        long maxHeapSize = Runtime.getRuntime().maxMemory() / (1024 * 1024);
        System.out.println("Max heap size (MB): " + maxHeapSize);
    }
}
Output
Max heap size (MB): 512
⚠️

Common Pitfalls

Common mistakes when increasing heap size include:

  • Setting -Xms larger than -Xmx, which causes JVM startup errors.
  • Using sizes without units, leading to confusion (always specify m or g for clarity).
  • Setting heap size too large for your system memory, causing your computer to slow down or crash.
  • Forgetting to apply the options when running the Java program (they must be passed to the java command, not the javac compiler).
bash
Wrong:
java -Xmx512m -Xms1024m YourProgram

Right:
java -Xms512m -Xmx1024m YourProgram
📊

Quick Reference

Here is a quick summary of heap size options:

OptionDescriptionExample
-XmsInitial heap size-Xms256m
-XmxMaximum heap size-Xmx1024m
Unitsk = KB, m = MB, g = GBe.g. 512m = 512 megabytes

Key Takeaways

Use -Xms to set the initial heap size and -Xmx to set the maximum heap size in Java.
Always specify units like m (megabytes) or g (gigabytes) when setting heap sizes.
Ensure -Xms is not larger than -Xmx to avoid JVM startup errors.
Set heap sizes according to your system's available memory to prevent crashes.
Pass heap size options to the java command, not javac.