RFR 8218227 : StringBuilder constructor throws confusing NegativeArraySizeException

Ivan Gerasimov ivan.gerasimov at oracle.com
Sat Feb 2 07:28:23 UTC 2019


Hello!

The spec of the constructors 
StringBuilder(String)/StringBuilder(CharSequence) states that the 
initial capacity of the builder will be set to the length of the 
argument plus 16.
This causes them to throw confusing NegativeArraySizeException when the 
argument's length is close to Integer.MAX_VALUE.

Let the arguments length be (Integer.MAX_VALUE - DELTA), like in the 
code below:

         String str = "Z".repeat(Integer.MAX_VALUE - DELTA);
         StringBuilder sb = new StringBuilder(str);

Currently the behavior is as following:
     0 <= DELTA <= 2 - unable to construct str,
     2 <= DELTA <= 15 - NegativeArraySizeException is thrown,
     16 <= DELTA <= 17 - OutOfMemoryError is thrown,
     DELTA >= 18 - works fine.

With the fix, OOM will be thrown for all DELTA <= 17.

Also the fix will make constructing a StringBuilder from UTF16 coded 
String slightly more efficient.

BUGURL: https://bugs.openjdk.java.net/browse/JDK-8218227
WEBREV: http://cr.openjdk.java.net/~igerasim/8218227/00/webrev/

Would you please help review the fix?

-- 
With kind regards,
Ivan Gerasimov



More information about the core-libs-dev mailing list