Java OutOfMemory Example


/ Published in: Java
Save to your folder(s)

This java code, when executed, throws OOM error.

Java Console:
...
Exception in thread "main" java.lang.OutOfMemoryError
...

Heapdump Data:
...
1STHEAPFREE Bytes of Heap Space Free: 0
1STHEAPALLOC Bytes of Heap Space Allocated: 66666600
...


Copy this code and paste it in your HTML
  1. import java.util.ArrayList;
  2. import java.util.List;
  3.  
  4. public class JavaOOM {
  5.  
  6. public static void main(String[] args) {
  7. System.out.println("Initial freeMemory: "+Runtime.getRuntime().freeMemory()/(1024*1024));
  8. oom1();
  9.  
  10. }
  11.  
  12. private static void oom1() {
  13. List<String> myList = new ArrayList<String>();
  14. for (long i=0; ; i++) {
  15. myList.add(new String(i+" - "+System.currentTimeMillis()));
  16. if (i%100000==0) {
  17. System.gc();
  18. System.out.println("i: "+i+", freeMemory: "+Runtime.getRuntime().freeMemory()/(1024*1024));
  19. }
  20. }
  21. }
  22.  
  23. }

URL: http://www.javacodegeeks.com/2013/08/understanding-the-outofmemoryerror.html

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.