Java.lang.OutOfMemoryError: Java heap space

I played with some sample collections from the Oracle site

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 would take to do for Double.MAX_VALUE. And I got this:

 Exception 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) 

Is there any way to fix this?

+1
source share
8 answers

Is there a way to create and save Double.MAX_VALUE objects in Collection ? No. There is not much RAM on Earth. Double.MAX_VALUE is approximately 2 times ten to the 308th power: this is 2 followed by more than 300 zeros. Give Best Buy to call, see how much they will charge to put it on your computer.

+17
source

Even if you have enough memory, an ArrayList can contain no more than Integer.MAX_VALUE elements. Double.MAX_VALUE far exceeds the specified limit.

In this case, you ran out of memory during add , which is why the list of arrays increased.

+5
source

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

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

+5
source

Instead of doing what you are doing now, you should just get 10 random doubles, add them to an ArrayList and sort them. This is basically what your method does.

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

+2
source

You are trying to extract about 10 ^ 308 values. These are many values.

+1
source

An increase in heap size will do. Just run the program with this argument:

 -Xmx512m 

It will increase your heap size to 512 MB. You can specify as many as you want: 1g, 2g, etc.

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

In your loop:

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

An ArrayList will simply add a value to the ArrayList if there is room. If not, this will increase the size of the ArrayList , and then continue adding.

So basically you are using all the memory allocated in your heap when you create this ArrayList . If you reduce the size of the ArrayList , you can keep it in memory.

0
source

Source: https://habr.com/ru/post/1482596/


All Articles