Backend Development 6 min read

Analyzing and Resolving OutOfMemoryError in Java MyBatis Applications

This article examines the frequent OutOfMemoryError incidents in a Java backend service, explains the underlying heap and metaspace causes, analyzes MyBatis source code that leads to memory leaks, demonstrates a reproducible scenario, and offers practical optimization recommendations to prevent OOM in production.

Java Architect Essentials
Java Architect Essentials
Java Architect Essentials
Analyzing and Resolving OutOfMemoryError in Java MyBatis Applications

In the preface, the author describes a recent production incident where the service repeatedly threw OutOfMemoryError (OOM), causing the entire distributed system to become unavailable and prompting an emergency restart.

The article then outlines two primary reasons for OOM: insufficient heap space due to strong references that prevent garbage collection, and metaspace exhaustion introduced in Java 8, which stores class metadata outside the heap.

Common heap‑memory‑overflow scenarios are listed, including loading excessively large query results, infinite loops that retain large objects, unreleased resource pools or I/O streams, and static collections that hold references indefinitely.

A free Spring Boot best‑practice project is recommended for further study.

In the analysis section, the author identifies the OOM as originating from MyBatis, where the framework stores concatenated SQL statements and parameters in a ContextMap (a subclass of HashMap ). When many threads execute large SQL with many parameters, the map retains these objects, preventing GC and eventually exhausting heap memory.

The author reproduces the issue by constructing large IN‑clauses, spawning 50 concurrent threads, and running the JVM with -Xmx256m -XX:+PrintGCDetails -XX:+HeapDumpOnOutOfMemoryError . Logs show frequent Full GC cycles leading to OOM.

Finally, the summary emphasizes that the root cause lies in oversized SQL concatenation and improper handling of MyBatis bindings; developers should optimize SQL generation, avoid massive parameter lists, and ensure resources are released promptly to prevent similar memory‑leak problems.

backendJavaPerformancememory leakMyBatisoom
Java Architect Essentials
Written by

Java Architect Essentials

Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.