12

I need to write 10,000 x 30,000 characters. will a single stringbuilder be able to acomodate all characters or should I think of an array of stringbuilders? I do not have access to the test cases, so I cannot actually verify it myself. Hope I will find the answer here.

Thanks in advance.

EDIT:

I tried to add 10000 x 30000 characters using a loop. I get the following exceptions.

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:2367)
at java.lang.AbstractStringBuilder.expandCapacity(AbstractStringBuilder.java:130)
at java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:114)
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:415)
at java.lang.StringBuilder.append(StringBuilder.java:132)
at Test.main(Test.java:19)

What to do with this "java heap space"?

Sam Hosseini
  • 813
  • 2
  • 9
  • 17
Victor Mukherjee
  • 10,487
  • 16
  • 54
  • 97

3 Answers3

18

The length is an int so it should hold up to 2GChar (4GB) assuming you have the memory. You are going to use "only" 600MB (300 million @ 2 bytes per character). Just be careful how many copies you end up making... i.e. toString().

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
  • I tried to add 10000x30000 characters using a loop and it gives errors. please see the edit. – Victor Mukherjee Oct 06 '12 at 16:49
  • 2
    You need to increase the heap space available to the VM with the `-Xms1024m -Xmx1536m` command-line option, which will set the initial allocation to 1GB and the max to 1.5GB. If you're running in a 32-bit environment this may be problematic. – Jim Garrison Oct 06 '12 at 21:36
3

What you need to worry about is the max heap size. It is not going to make any difference whether you use single or multiple StringBuilder objects.

Sameer
  • 4,379
  • 1
  • 23
  • 23
1

As long as the length of the character sequence contained in the string builder does not exceed the capacity, it is not necessary to allocate a new internal buffer. If the internal buffer overflows, it is automatically made larger. And it gives you the max number of chars this StringBuilder instance memory can hold at this time.

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103