A2oz

How to Add JVM Arguments in Java?

Published in Java Development 2 mins read

You can add JVM arguments to your Java program in several ways:

1. Using the Command Line

This is the most common method for adding JVM arguments. When you run your Java program using the java command, you can append the arguments after the class name.

Example:

java -Xms512m -Xmx1024m -XX:+UseG1GC MyProgram

In this example:

  • -Xms512m sets the initial heap size to 512 MB.
  • -Xmx1024m sets the maximum heap size to 1024 MB.
  • -XX:+UseG1GC enables the G1 garbage collector.

2. Using an IDE

Most Integrated Development Environments (IDEs) allow you to specify JVM arguments for your Java program. You can usually find this option in the project settings or run configurations.

Example:

In IntelliJ IDEA, you can add JVM arguments in the "Run/Debug Configurations" dialog under the "VM options" field.

3. Using a Configuration File

You can also define JVM arguments in a configuration file, such as a run.sh script. This approach is useful for running your program automatically or with specific settings.

Example:

#!/bin/bash
java -Xms512m -Xmx1024m -XX:+UseG1GC MyProgram

4. Using the java.util.Properties Class

You can programmatically set JVM arguments using the java.util.Properties class. This approach is less common but can be useful for dynamic configuration.

Example:

import java.util.Properties;

public class MyProgram {
    public static void main(String[] args) {
        Properties props = System.getProperties();
        props.setProperty("java.awt.headless", "true");
        // ...
    }
}

This code sets the java.awt.headless property to true, which can be useful for running your program without a graphical user interface.

Common JVM Arguments

Here are some commonly used JVM arguments:

  • Heap size:
    • -Xms: Initial heap size.
    • -Xmx: Maximum heap size.
  • Garbage collector:
    • -XX:+UseG1GC: Enables the G1 garbage collector.
    • -XX:+UseParallelGC: Enables the parallel garbage collector.
  • Other arguments:
    • -XX:+PrintGCDetails: Enables detailed garbage collection logging.
    • -XX:+HeapDumpOnOutOfMemoryError: Creates a heap dump file when an OutOfMemoryError occurs.

Remember that the specific JVM arguments and their effects may vary depending on the Java version and operating system.

Related Articles