
This simple example explains how to iterate through Java Iterator and avoid possible OutOfMemory (OOM) in Java. This post is filed under Java Web Tutorial.
Possible reason: forget to use
Iterator.next()
inside loop.
Good code: Below example just iterator through ArrayList (Collection) and returns the same value with the help of java.util.Iterator
.

package com.crunchify; import java.util.ArrayList; import java.util.Iterator; /** * @author Crunchify.com */ public class CrunchifyIteratorOOM { public static void main(String[] args) { ArrayList<String> company = new ArrayList(); company.add("eBay"); company.add("Paypal"); company.add("Google"); Iterator comapnyIterator = company.iterator(); int i= 1; while(comapnyIterator.hasNext()) { String companyName = (String)comapnyIterator.next(); System.out.print(i + " "); System.out.println(companyName); i++; } } }
Output:
1 eBay 2 Paypal 3 Google
Bad code: Now just comment out below two lines from above code.
// String companyName = (String)comapnyIterator.next(); // System.out.println(companyName);
Output:
You should see your Java program going into infinite loop which eventually cause OOM.
What is the best practice? Always use enhanced Java 8 for loop.
package com.crunchify; import java.util.ArrayList; import java.util.Iterator; /** * @author Crunchify.com */ public class CrunchifyIteratorOOM { public static void main(String[] args) { ArrayList<String> company = new ArrayList(); company.add("eBay"); company.add("Paypal"); company.add("Google"); // Same example as above but enhanced for loop. for (String s : company) { System.out.println(s); } } }
How can I check if memory usage is increasing over time?
- Run this program
- Go to macOS Terminal (in Mac) or Command prompt (in Windows)
- Type: jConsole and Enter
- Select process associated with your java program as in below diagram

- Monitor / Analyse Memory/ CPU usage and you should see it increase over time and finally OOM.

Sometimes this small thing could leads to Memory Leak/ OOM in major production projects.
The post Java Iterator: OutOfMemory (OOM) Scenario appeared first on Crunchify.
0 Commentaires