Video in progress
Where is memory leaking in this code?
@RestController
class PaymentController {
private static final List<PaymentRequest> AUDIT = new ArrayList<>();
@PostMapping("/pay")
ResponseEntity<Void> pay(@RequestBody PaymentRequest req) {
AUDIT.add(req);
paymentService.process(req);
return ResponseEntity.ok().build();
}
}
AUDIT is a static list; an entry is added to it on every request but never removed. A static field lives as long as the class does (in practice until the application ends), so the heap slowly fills up.
📖 Answer
From the GC's point of view everything is correct: AUDIT -> static field -> GC root. Every PaymentRequest in the list is alive. At 1 million payments a day, you get OutOfMemoryError: Java heap space in a few days.
A leak like this doesn't show up in testing: nothing happens with 100 requests. On prod, on the graph, the low line of the heap after each GC is a bit higher every day.
An extra problem: ArrayList is not thread-safe, so if several requests add at the same time, the data gets corrupted or you get an ArrayIndexOutOfBoundsException.
What to do, depending on the goal:
- if you need an audit, write it to a DB, a log or Kafka, not to memory;
- if you need the last N entries, use a bounded structure (for example, Caffeine with
maximumSize(10_000)); - if you don't need it at all, remove it.
In a heap dump this is visible immediately: MAT's "Leak Suspects" points to the PaymentController class and the huge ArrayList inside it.
Sign up to mark studied questions and save your progress.