Question
What causes the java.lang.OutOfMemoryError: PermGen space error when running a web application, and how can it be resolved?
// Example snippet to set the PermGen space size in a JVM argument:
-java -XX:PermSize=128m -XX:MaxPermSize=256m
Answer
The java.lang.OutOfMemoryError: PermGen space error occurs when the Permanent Generation (PermGen) area of the Java Virtual Machine (JVM) runs out of memory. This usually happens in web applications when they load a large number of classes, especially during development or when using frameworks like Spring or Hibernate. The PermGen space keeps metadata related to the classes and methods of the loaded application, so it is crucial to manage its size effectively to avoid this error.
// JVM options to increase PermGen space
-java -XX:PermSize=128m -XX:MaxPermSize=256m
Causes
- Excessive usage of class loaders which leads to a large number of classes being loaded.
- Using frameworks that generate proxy classes at runtime, increasing the overall number of loaded classes.
- Deployment of many web applications in a single JVM, leading to memory exhaustion in PermGen area. It is common during testing with multiple contexts.
- Java applications that dynamically generate classes, like some ORM tools.
Solutions
- Increase the PermGen space by configuring the JVM options with -XX:PermSize and -XX:MaxPermSize. For example, use `-XX:PermSize=128m -XX:MaxPermSize=256m` to allocate more memory to PermGen.
- Upgrade to Java 8 or later, where PermGen space is replaced by Metaspace, which grows dynamically, minimizing the risk of this error.
- Optimize code to reduce the number of classes generated, such as refactoring code to eliminate the need for excessive proxies.
- If using a framework, check for configurations or settings that minimize the creation of temporary classes.
Common Mistakes
Mistake: Not setting the PermGen size in a development environment, leading to frequent restarts for testing.
Solution: Set a comfortable PermGen size in your IDE's run configurations.
Mistake: Assuming that a web application can run indefinitely in a shared JVM without monitoring memory usage.
Solution: Regularly monitor memory usage metrics to catch potential leaks before they trigger OOM errors.
Mistake: Not refactoring code that creates excessive classes with frameworks.
Solution: Audit the usage of third-party libraries and frameworks to avoid unnecessary proxy or dynamic class generation.
Helpers
- java.lang.OutOfMemoryError
- PermGen space
- web application memory issue
- Java memory management
- JVM PermGen configuration