On Fri, 4 Dec 2020 16:02:33 GMT, Roger Riggs <rri...@openjdk.org> wrote:

>> This rewrites the doc of ArraysSupport.newLength, adds detail to the 
>> exception message, and adds a test. In addition to some renaming and a bit 
>> of refactoring of the actual code, I also made two changes of substance to 
>> the code:
>> 
>> 1. I fixed a problem with overflow checking. In the original code, if 
>> oldLength and prefGrowth were both very large (say, Integer.MAX_VALUE), this 
>> method could return a negative value. It turns out that writing tests helps 
>> find bugs!
>> 
>> 2. Under the old policy, if oldLength and minGrowth required a length above 
>> SOFT_MAX_ARRAY_LENGTH but not above Integer.MAX_VALUE, this method would 
>> return Integer.MAX_VALUE. That doesn't make any sense, because attempting to 
>> allocate an array of that length will almost certainly cause the Hotspot to 
>> throw OOME because its implementation limit was exceeded. Instead, if the 
>> required length is in this range, this method returns that required length.
>> 
>> Separately, I'll work on retrofitting various call sites around the JDK to 
>> use this method.
>
> Nice clean description of the algorithm.

For what it's worth, the following code:

var list = Collections.nCopies(Integer.MAX_VALUE - 3, "");
var list2 = new ArrayList<>(list);
list2.addAll(list);

results in `java.lang.NegativeArraySizeException: -8` where the -8 is returned 
by `ArraysSupport.newLength`. This is a demonstration of the problem with 
overflow checking that is fixed by this change.

-------------

PR: https://git.openjdk.java.net/jdk/pull/1617

Reply via email to