Sitemap

Memory Leak When Injecting Prototype Beans into Spring Singleton Beans — Full Case Study

4 min read6 hours ago
Press enter or click to view image in full size
AI image

Interactive Interview Theme:
*“You’re in a
senior backend interview.

The interviewer says:
‘We have a memory leak. A List in a base class keeps growing — even after we marked the beans as @Scope("prototype"). Why? And how do you fix it?’

Can you explain with logs, source-level insight, and two production fixes — all while staying calm?”*

Let’s simulate the real incident — and turn it into a learning masterpiece.

Problem Background

A stateful abstract service accumulates 1 million characters per call in a List<String>.
Subclasses are injected into a singleton controller via List<SayService>.

Expectation:
Each HTTP request → new SayHello and SayBye instances → fresh data list.

Reality:
data.size() keeps growingOOM after 100+ requests.

The Code That Broke Production

// Stateful base class — DANGER!
public abstract class SayService {
List<String> data = new ArrayList<>(); // ← Shared per instance

public void say() {
data.add(IntStream.rangeClosed(1, 1_000_000)…
Umesh Kumar Yadav
Umesh Kumar Yadav

Written by Umesh Kumar Yadav

Seasoned software developer with 12+ years of experience, specializing in Java, Spring Boot, Kafka, Redis, and system architecture.

No responses yet

Write a response