← Back to Questions
Java

What is OutOfMemoryError in Java?

Learn What is OutOfMemoryError in Java? with simple explanations, real-time examples, interview tips and practical use cases.

What is OutOfMemoryError in Java?

OutOfMemoryError (OOM) in Java occurs when JVM cannot allocate enough memory for new objects.

In simple words:

When JVM memory becomes full and no more memory can be allocated, Java throws OutOfMemoryError.


Why OutOfMemoryError Happens?

OutOfMemoryError happens because:

  • Heap memory becomes full
  • Memory leaks exist
  • Too many objects are created
  • Improper JVM memory configuration
  • Large data processing exceeds limits

OutOfMemoryError Flow Diagram


Application Running

      |
      v

Objects Continuously Created

      |
      v

Heap Memory Becomes Full

      |
      v

Garbage Collector Unable to Free Enough Memory

      |
      v

OutOfMemoryError Thrown


Common OutOfMemoryError Message

java.lang.OutOfMemoryError:
Java heap space

What Happens Internally?

  • Application requests memory
  • JVM tries to allocate heap space
  • GC attempts cleanup
  • No sufficient memory available
  • JVM throws OutOfMemoryError

Basic Example

List list =
    new ArrayList<>();

while(true) {

    list.add(
        UUID.randomUUID().toString()
    );

}

Problem

Objects keep growing continuously until heap memory becomes full.


Memory Exhaustion Flow


Objects Added Repeatedly

      |
      v

Heap Usage Increases

      |
      v

GC Runs Frequently

      |
      v

Memory Still Insufficient

      |
      v

OutOfMemoryError


Main Types of OutOfMemoryError

  • Java Heap Space
  • GC Overhead Limit Exceeded
  • Metaspace
  • Unable to Create New Native Thread
  • Direct Buffer Memory
  • Requested Array Size Exceeds VM Limit

1. Java Heap Space

Most common OutOfMemoryError.


Cause

  • Heap memory becomes full
  • Too many objects
  • Memory leaks

Example Error

java.lang.OutOfMemoryError:
Java heap space

2. GC Overhead Limit Exceeded

Occurs when Garbage Collector spends too much time cleaning memory but recovers very little space.


Error Example

java.lang.OutOfMemoryError:
GC overhead limit exceeded

Internal Flow


GC Running Frequently

      |
      v

Very Little Memory Recovered

      |
      v

Application Performance Degrades

      |
      v

OOM Thrown


3. Metaspace OutOfMemoryError

Occurs when class metadata memory becomes full.


Common Causes

  • Too many dynamically generated classes
  • ClassLoader leaks

Error Example

java.lang.OutOfMemoryError:
Metaspace

4. Unable to Create New Native Thread

Occurs when JVM cannot create additional threads.


Common Causes

  • Too many threads
  • OS thread limits reached
  • Insufficient native memory

Error Example

java.lang.OutOfMemoryError:
unable to create new native thread

5. Direct Buffer Memory

Occurs when direct memory allocation exceeds configured limits.


Used In

  • NIO operations
  • Netty
  • Kafka
  • High-performance networking

Error Example

java.lang.OutOfMemoryError:
Direct buffer memory

6. Requested Array Size Exceeds VM Limit

Occurs when application tries to create extremely large arrays.


Example

int[] arr =
    new int[Integer.MAX_VALUE];

Error Example

java.lang.OutOfMemoryError:
Requested array size exceeds VM limit

Difference Between Exception and Error

Feature Exception Error
Recoverable Usually Yes Usually No
Handled By Application Logic JVM/System
Example IOException OutOfMemoryError
Severity Medium Critical

How to Prevent OutOfMemoryError?

  • Avoid memory leaks
  • Use efficient data structures
  • Clear unused references
  • Optimize object creation
  • Use connection pooling
  • Tune JVM heap properly

Memory Leak Example

Map cache =
    new HashMap<>();

while(true) {

    cache.put(
        UUID.randomUUID().toString(),
        new Object()
    );

}

Problem

Objects remain referenced forever. GC cannot remove them.


How to Fix?

  • Remove unused cache entries
  • Use eviction policies
  • Use WeakHashMap if appropriate

Heap Dump

Heap dump is a memory snapshot used to analyze OutOfMemoryError.


Heap Dump JVM Option

-XX:+HeapDumpOnOutOfMemoryError

Heap Dump Flow


OOM Occurs

      |
      v

Heap Dump Generated

      |
      v

Memory Analysis Performed

      |
      v

Root Cause Identified


Useful Memory Analysis Tools

  • VisualVM
  • Eclipse MAT
  • JProfiler
  • Java Flight Recorder
  • Grafana + Prometheus

JVM Heap Configuration

-Xms512m
-Xmx2g

Meaning

  • Xms → Initial heap size
  • Xmx → Maximum heap size

Example

java -Xms1g -Xmx4g app.jar

OutOfMemoryError in Banking Systems

Banking systems may face OOM because of:

  • Large transaction loads
  • Improper caching
  • Massive concurrent users
  • Memory-intensive reports

Why Critical?

  • Application downtime
  • Transaction failures
  • Customer impact

OutOfMemoryError in E-Commerce Systems

E-commerce platforms may face OOM due to:

  • Huge shopping cart data
  • Product caching
  • Flash-sale traffic spikes
  • Session memory overload

OutOfMemoryError in Spring Boot

Spring Boot applications may experience OOM because of:

  • Large REST payloads
  • Improper caching
  • Thread leaks
  • Huge JSON processing

Spring Boot Example

@RestController
public class UserController {

}

Large request processing may create excessive objects.


OutOfMemoryError in Microservices

Microservices architectures may face OOM due to:

  • Kafka consumer backlog
  • Distributed cache overload
  • High API concurrency
  • Container memory limits

Docker and Kubernetes Impact

Containerized applications require careful memory tuning.


Container Memory Flow


Container Memory Limited

      |
      v

Application Creates Excess Objects

      |
      v

Container Memory Exhausted

      |
      v

OOM / Container Restart


Modern Monitoring Tools

  • Prometheus
  • Grafana
  • New Relic
  • Datadog
  • Elastic APM

OOM Monitoring Flow


Application Running

      |
      v

Heap Metrics Collected

      |
      v

Memory Growth Detected

      |
      v

Alerts Triggered


Advantages of Proper Memory Management

  • Improved application stability
  • Reduced downtime
  • Better scalability
  • Lower GC pauses

Disadvantages of Ignoring OOM Issues

  • Application crashes
  • Performance degradation
  • High infrastructure cost
  • Production outages

Common Interview Mistake

Many developers think increasing heap size always fixes OOM.

Actually:

  • Root cause analysis is required.
  • Memory leaks may still exist.

Another Common Mistake

Many developers think GC automatically prevents all OOM issues.

Actually:

  • GC cannot remove reachable objects.

Best Practices

  • Monitor heap regularly
  • Use efficient collections
  • Avoid unnecessary caching
  • Optimize thread usage
  • Analyze heap dumps during OOM
  • Use proper JVM tuning

Realtime Enterprise Example

Microservice Memory Leak


Kafka Messages Received

      |
      v

Objects Added to Cache

      |
      v

Cache Never Cleared

      |
      v

Heap Memory Full

      |
      v

OutOfMemoryError


Related Learning Topics


Professional Interview Answer

OutOfMemoryError in Java occurs when JVM cannot allocate enough memory for application execution. It typically happens when heap memory becomes full due to excessive object creation, memory leaks, improper caching, large thread creation, or incorrect JVM memory configuration. Common types include Java Heap Space, GC Overhead Limit Exceeded, Metaspace, Direct Buffer Memory, and Unable to Create New Native Thread. OutOfMemoryError is considered a critical JVM-level error and often requires memory optimization, heap dump analysis, garbage collection tuning, and proper application design. Enterprise applications, Spring Boot systems, banking platforms, cloud-native microservices, Kafka-based architectures, and distributed systems must carefully monitor and optimize memory usage to prevent OutOfMemoryError in production environments.


Frequently Asked Questions

What is OutOfMemoryError in Java?

It occurs when JVM cannot allocate enough memory for objects or application execution.

What is the most common OutOfMemoryError?

Java heap space OutOfMemoryError is the most common type.

Can increasing heap size fix OutOfMemoryError?

Sometimes yes, but memory leaks and poor design must also be fixed.

What causes memory leaks?

Unused objects remaining referenced cause memory leaks.

How do you analyze OutOfMemoryError?

Using heap dumps and memory analysis tools like VisualVM or Eclipse MAT.

Why this Java question is important?

This interview question helps candidates understand real-time backend development concepts, practical problem solving, coding fundamentals, system design basics and production-ready application behavior.

Practice this question carefully for Java backend roles, Spring Boot developer interviews, microservices interviews, company interviews and full-stack developer preparation.

About the Author

Naresh Kumar is a Senior Java Backend Engineer with experience building enterprise applications using Java, Spring Boot, Microservices, Docker, Kubernetes and Cloud technologies.