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

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.