Logs say OutOfMemoryError – how would you investigate?

When an OutOfMemoryError occurs, it indicates that the JVM cannot allocate enough memory for new objects. The investigation should focus on identifying whether the issue is caused by a memory leak, insufficient heap allocation, excessive object creation, large data structures, or improper resource management.

Key Points: • Check JVM memory settings such as -Xms and -Xmx to verify whether the allocated heap is sufficient for the application's workload. • Analyze heap dumps using tools like Eclipse MAT, VisualVM, or jmap to identify memory leaks, large objects, and excessive object retention. • Review application code for common issues such as unbounded collections, improper caching, static object references, excessive object creation, and unclosed resources.

Example: Suppose an application stores user session data in a HashMap but never removes expired sessions. Over time, the map continues to grow, consuming heap memory until the JVM eventually throws an OutOfMemoryError. A heap dump analysis would reveal the large collection retaining most of the memory.

Interview Tip: A concise interview answer is: To investigate an OutOfMemoryError, I first identify the type of memory issue, review JVM heap settings, collect heap dumps, and analyze them using tools like Eclipse MAT or VisualVM. I then look for memory leaks, large collections, excessive object retention, and recent code changes. Finally, I validate the fix through monitoring and load testing to ensure the issue does not recur.