Over a million developers have joined DZone.

Java - OOM Example

DZone's Guide to

Java - OOM Example

Free Resource

Learn how to troubleshoot and diagnose some of the most common performance issues in Java today. Brought to you in partnership with AppDynamics.

I did an experiment today and wrote a code snippet that would ultimately fail with an OutOfMemory (OOM) error. There are 2 variations in what I did.

1. Class with explicit System.gc() call

2. Class without explicit System.gc() call

As expected, both the executions fail with OOM. But what is interesting is the free memory pattern generated by both. Please refer to the attachment for details and share your thoughts/comments on this.

Here is the code.

import java.util.ArrayList;
import java.util.List;

public class JavaOOM {

   public static void main(String[] args) {
     System.out.println("Initial freeMemory: "+Runtime.getRuntime().freeMemory()/(1024*1024));

   private static void oom1() {
     List<String> myList = new ArrayList<String>();
     for (long i=0; ; i++) {
       if (i%100000==0) {
         System.out.println("i: "+i+", freeMemory: "+Runtime.getRuntime().freeMemory()/(1024*1024));


Understand the needs and benefits around implementing the right monitoring solution for a growing containerized market. Brought to you in partnership with AppDynamics.


Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}