开发者

java.lang.OutOfMemoryError : Java heap space

I was playing with some examples of Collections from Oracle website

public class Timing {

    public static void method(){

        List numbers = new ArrayList();

        for (double i = 1; i <= Double.MAX_VALUE; i++)
        numbers.add(new Double(i));

        Collections.shuffle(numbers);
        List winningcombination = numbers.subList(0, 10);
        Collections.sort(winningcombination);
    }

    public static void main(String[] args)
    {
        long start = System.currentTimeMillis();
        method();
        long end = System.currentTimeMillis();
        System.out.println("time elapsed : " + (end-start));
    }
}

I tried to see how long it will take to do it for Double.MAX_VALUE. And I got this :

Exce开发者_如何学Cption in thread "main" java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOf(Unknown Source)
    at java.util.Arrays.copyOf(Unknown Source)
    at java.util.ArrayList.ensureCapacity(Unknown Source)
    at java.util.ArrayList.add(Unknown Source)

I there a way to fix this ?


Is there a way to allow you to create and store Double.MAX_VALUE objects in a Collection? No. There's not that much RAM on Earth. Double.MAX_VALUE is about 2 times ten to the 308th power: that's 2 followed by over 300 zeros. Give Best Buy a call, see how much they'd charge to put that in your computer.


Even if you had enough memory, ArrayList can have at most Integer.MAX_VALUE elements. Double.MAX_VALUE far exceeds said limit.

In this case, you ran out of memory during an add that caused the array list to grow.


Yet another reason why your code cannot work: double can only represent integers exactly up to about 2^52 - after that, i++ will have no effect and the for loop will never terminate.

You should never use floating-point variables as loop counters. Use int or long instead.


Instead of doing what you are currently doing, you should just obtain 10 random doubles, add them to an ArrayList and sort it. That is basically what your method is doing.

To obtain a random double, look at Random.nextDouble().


You are trying to allocate of the order of 10^308 values. That's a lot of values.


Increasing the size of the heap will do. Just run the program with this argument:

-Xmx512m

It will increase your heap size to 512 MB. You can specify as much as you want: 1g, 2g and so on.


for (double i = 1; i <= Integer.MAX_VALUE; i++)
        numbers.add(new Double(i));


In you loop:

for (double i = 1; i <= Double.MAX_VALUE; i++)
    numbers.add(new Double(i));

An ArrayList will just add the value to the ArrayList if there is room. If not it will increase the size of the ArrayList and then continue adding.

So what you are basically doing is using all the memory allocated in your heap when you are creating this ArrayList. If you make your ArrayList smaller you should be able to hold it in memory.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜