-3

I have simple program which gives me out of memory issue:

public static void main(String[] args) {

    int i[] = new int[457560000];
}

This throws below error :

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

I have tried setting VM arguments in my eclpse like this : -Xms1024M -Xmx2048M, but still getting same error.

I don't need such a big array, but I had an issue with image processing where the image size is very big. While debugging I observed that AWT packages was trying to create this array and failing with memory issues.

How to fix this issue? How much memory I need to set before I run this code?

update:

I also tried with 6GB setting for Xmx under eclipse run configuration VM settings, my machine got hanged for some time but again faced same error.

learner
  • 6,062
  • 14
  • 79
  • 139
  • Why do you need to create an array of that size? Java is throwing the error because it doesn't have enough memory to create a variable array that large. – Dylan Wheeler Jul 05 '16 at 16:19
  • 7
    do youreally need 456 million integers??? – ΦXocę 웃 Пepeúpa ツ Jul 05 '16 at 16:21
  • 1
    Possible duplicate of [How to deal with "java.lang.OutOfMemoryError: Java heap space" error (64MB heap size)](http://stackoverflow.com/questions/37335/how-to-deal-with-java-lang-outofmemoryerror-java-heap-space-error-64mb-heap) – Filburt Jul 05 '16 at 16:22
  • Even if you really do need that much space, allocating an array of that size is bulky and will run into memory issues. Generally speaking, when I have an array that I know is gonna be that big I'd use a list or arraylist instead. – Rabbit Guy Jul 05 '16 at 16:30
  • @ΦXocę웃Пepeúpa, I have updated my question with why I am facing this issue. Can you please help me how to fix this? – learner Jul 05 '16 at 17:01
  • @Filburt, Updated my post with details. How can I solve this issue? What memory I need to set before running my program? – learner Jul 05 '16 at 17:02
  • Where are you setting the VM arguments? These need to be in the Run Configuration for your program (and the -Xmx may well need to be larger). – greg-449 Jul 05 '16 at 17:12
  • @greg-449, I tried with 6G for Xmx option, for eclipse run configuration. My machine completely blocked for sometime and later saw same error message. – learner Jul 05 '16 at 19:23

1 Answers1

0

Your Run Configruation of the given code snippet requires at least -Xmx2640M depending which JRE you use.

As -Xmx is the maximum that is used only if necessary you can run your program with for instance -Xmx256000M and then find out how many memory was actually used.

howlger
  • 31,050
  • 11
  • 59
  • 99
  • I have already set that, you can see my question, I mentioned it. – learner Jul 05 '16 at 19:21
  • If I run your code snippet with `-Xmx2048M` an _OutOfMemoryError_ occures and with `-Xmx2640M` there will be no error. I used a 64 bit jdk1.8.0_60 on Windows to run your snippet. What JRE do you use? – howlger Jul 05 '16 at 20:26