Heap Size Configuration
JVM Heap Size Parameters
Initial and Maximum Heap Size
graph LR
A[JVM Heap Size] --> B[Initial Heap Size]
A --> C[Maximum Heap Size]
Parameter |
Description |
Example |
-Xms |
Initial heap size |
-Xms256m |
-Xmx |
Maximum heap size |
-Xmx2g |
Configuration Methods
1. Command Line Configuration
## Set initial heap size to 512MB
java -Xms512m MyApplication
## Set maximum heap size to 2GB
java -Xmx2048m MyApplication
## Combined configuration
java -Xms512m -Xmx2g MyApplication
2. Environment Variable Configuration
## In .bashrc or .bash_profile
export JAVA_OPTS="-Xms512m -Xmx2g"
3. Programmatic Detection
public class HeapSizeDemo {
public static void main(String[] args) {
// Get runtime memory information
Runtime runtime = Runtime.getRuntime();
long maxMemory = runtime.maxMemory();
long totalMemory = runtime.totalMemory();
long freeMemory = runtime.freeMemory();
System.out.println("Max Memory: " + maxMemory / (1024 * 1024) + " MB");
System.out.println("Total Memory: " + totalMemory / (1024 * 1024) + " MB");
System.out.println("Free Memory: " + freeMemory / (1024 * 1024) + " MB");
}
}
Best Practices
Recommended Configuration Strategies
graph TD
A[Heap Size Strategy] --> B[Initial == Maximum]
A --> C[Leave Headroom for OS]
A --> D[Monitor Application Performance]
- Match initial and maximum heap sizes
- Leave memory for operating system
- Use monitoring tools
- Adjust based on application needs
Advanced Configuration Options
Garbage Collector Specific Settings
## Use G1 Garbage Collector
java -XX:+UseG1GC -Xms1g -Xmx4g MyApplication
## Parallel Garbage Collector
java -XX:+UseParallelGC -Xms512m -Xmx2g MyApplication
Monitoring Heap Usage
Tool |
Purpose |
Platform |
jconsole |
GUI Monitoring |
Cross-platform |
jstat |
Command-line Statistics |
Linux/Unix |
visualvm |
Comprehensive Profiling |
Cross-platform |
LabEx Tip
At LabEx, we recommend systematic approach to heap configuration:
- Start with conservative settings
- Monitor performance
- Incrementally optimize based on metrics