Unexepcted OutOfMemoryError from Arrays.deepToString
Pavel Rappo
pavel.rappo at oracle.com
Sat Oct 9 12:07:10 UTC 2021
This error has two causes. The first cause is that the VM cannot allocate arrays whose length exceeds Integer.MAX_VALUE - 8 (MAX_ARRAY_SIZE). The second cause is that Arrays.deepToString tries to pre-allocate 20 chars per string representation for each array element and maxes out at Integer.MAX_VALUE, which is above MAX_ARRAY_SIZE. One solution would be to change Arrays.deepToString to max out at MAX_ARRAY_SIZE.
Separately, java.lang.AbstractStringBuilder#MAX_ARRAY_SIZE seems unused; I wonder how that happened.
-Pavel
> On 9 Oct 2021, at 11:38, Andrey Turbanov <turbanoff at gmail.com> wrote:
>
> Hello.
> I came across unexpected behaviour of Arrays.deepToString method.
> It throws OOM even on non-huge arrays.
> For example this code:
>
> int size = Integer.MAX_VALUE / 19;
> Integer[] integers = new Integer[size];
> Arrays.fill(integers, 0);
> System.out.println(Arrays.deepToString(integers));
>
> Fails with following stack trace:
>
> Exception in thread "main" java.lang.OutOfMemoryError: Requested array
> size exceeds VM limit
> at java.base/java.lang.AbstractStringBuilder.<init>(AbstractStringBuilder.java:86)
> at java.base/java.lang.StringBuilder.<init>(StringBuilder.java:112)
> at java.base/java.util.Arrays.deepToString(Arrays.java:5160)
>
>
> I believe it should be able to handle such arrays and not throw OOM
>
>
> Andrey Turbanov
More information about the core-libs-dev
mailing list