HTML5 Zone is brought to you in partnership with:

A java developer and enthusiast with over 10 years of experience in Java and related technologies. Navaneethakrishnan has posted 4 posts at DZone. You can read more from them at their website. View Full User Profile

Java - OOM Example

  • submit to reddit

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));


Published at DZone with permission of its author, Navaneethakrishnan Ramakrishnan.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)