0

When i run the below program i got the exception when for loop begins its execution at i=1031521. How to over come memory usage of this type?

class wwww
    {
        public static void main(String args[])
        {
            String abc[]=new String[4194304];
            String wwf="";
            int s_count=524286;
            for(int i=0;i<4194304;i++)
            {
                System.out.println("----------enter--------"+i);
                abc[i]=""+i;
                System.out.println("----------exit--------"+i);
            }
        }
    }

The exception is:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOf(Arrays.java:2882)
    at java.lang.AbstractStringBuilder.expandCapacity(AbstractStringBuilder.
java:100)
    at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:390
)
    at java.lang.StringBuilder.append(StringBuilder.java:119)
    at wwww.main(wwww.java:12)
vij
  • 143
  • 1
  • 2
  • 18
  • 1
    you can find your answer here. http://stackoverflow.com/questions/4308364/where-can-i-permanently-set-java-heap-size-on-windows-pc – Ali Imran Nov 28 '12 at 06:46

3 Answers3

1

This is because your your uses up all the heap space allocated to your jvm.

You can use argument while running the program to specify the heap size that you would like to allocate.

This is an example:

java -Xmx256m MyClass

Here a maximum of 256 MB of heap space will be allocated

Abubakkar
  • 15,488
  • 8
  • 55
  • 83
1

How to over come memory usage of this type?

Don't perform memory usage of this type. You are creating 4194304 strings, of the general form ""+i. You don't need 4194304 strings of that form all at once. You only need one of them at a time, if any, and you can create it every time you need it.

user207421
  • 305,947
  • 44
  • 307
  • 483
0

You could either:

  1. Increase the heap size that you give to your program. This is done via the -Xmx command-line argument to java.
  2. Re-engineer the program to use less memory. Do you really need to keep all those strings in memory at once?
NPE
  • 486,780
  • 108
  • 951
  • 1,012