-
December 28th, 2010, 10:33 PM
#1
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space help
Hi so I've been having trouble with this one exception I've been getting. It says it's on line 22 but I don't understand why I'm getting it. BTW I'm using Eclipse on a Mac.
Code:
Code:
import java.util.*;
public class ProjectEulerProb2 {
int firstInt=1, secondInt=0, thirdInt = 0;
ArrayList<Integer> list = new ArrayList<Integer>();
public static void main(String args[]){
ProjectEulerProb2 prob = new ProjectEulerProb2();
prob.doIt();
}
public void doIt(){
for(long i = 0; i<=4000000;i++){
secondInt = firstInt+firstInt;
list.add(secondInt);
firstInt = secondInt;
list.add(firstInt);
thirdInt = firstInt+secondInt;
list.add(thirdInt);
}
}
}
Exception:
Code:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:2760)
at java.util.Arrays.copyOf(Arrays.java:2734)
at java.util.ArrayList.ensureCapacity(ArrayList.java:167)
at java.util.ArrayList.add(ArrayList.java:351)
at ProjectEulerProb2.doIt(ProjectEulerProb2.java:22)
at ProjectEulerProb2.main(ProjectEulerProb2.java:11)
-
December 29th, 2010, 08:23 AM
#2
Re: Exception in thread "main" java.lang.OutOfMemoryError: Java heap space help
It says it's on line 22 but I don't understand why I'm getting it
The message tells you why you are getting it - you've run out of heap space. You are creating a very large ArrayList and there isn't enough free heap space to hold it all.
If you need more heap space start the application with the command line switch:
-XmxSizeUnits
for example:
To set a max heap size of 128Mb use: java -Xmx128m
To set a max heap size of 640kb use: java -Xmx640k
I believe the default size depends on your OS, the available memory etc but generally appears to be around 128Mb so I suggest you try setting it to 256Mb and if that doesn't work try 512Mb.
BTW for efficiency reasons when dealing with such a large list you are better off specifying and initial size when instantiating the ArrayList as this saves the list from repeatedly resizing the backing array. Or if you know the actual size of the list, you are much better off just using an int array. An int array saves converting all those int values to Integer objects to store in the ArrayList.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|