Java – deliberately cause OutOfMemoryException

Tuesday, August 4th, 2015

package test;

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

public class OutOfMemory {
    public static void main(String[] args) {
    	final List<String>list = new ArrayList<String>();
    	int i = 1;
    	while(true) {
			list.add(new String(System.nanoTime()+""));
			list.addAll(list);
			System.out.println(i+ " " + Runtime.getRuntime().freeMemory());
			i++;
		}
    	
    }
}

After a few seconds should output something like:


Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:2245)
at java.util.Arrays.copyOf(Arrays.java:2219)
at java.util.ArrayList.grow(ArrayList.java:213)
at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:187)
at java.util.ArrayList.addAll(ArrayList.java:532)
at test.OutOfMemory.main(OutOfMemory.java:12)

You can leave a response, or trackback from your own site.

Tags:
Posted in: Interview Questions



Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>