Skip to content

Instantly share code, notes, and snippets.

@Abacn
Created November 21, 2023 21:21
Show Gist options
  • Save Abacn/e8fda767f53e723db6d71f21f4db2187 to your computer and use it in GitHub Desktop.
Save Abacn/e8fda767f53e723db6d71f21f4db2187 to your computer and use it in GitHub Desktop.
NegativeArraySizeException when constructing large (>1GB) string in Java9+
package org.example;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
// In Java8: java.lang.OutOfMemoryError: Java heap space
// In Java9+: java.lang.NegativeArraySizeException: -1894967266
public class Main {
static byte[] generateData() {
int asciisize = 1_200_000_000;
byte[] nonAscii = "非アスキー".getBytes();
int nonAsciiSize = nonAscii.length;
// 1 GB
byte[] arr = new byte[asciisize + nonAsciiSize];
for (int i=0; i<asciisize; ++i) {
arr[i] = (byte)('0' + (i % 40));
}
for(int i=0; i<nonAsciiSize; ++i) {
arr[i + asciisize] = nonAscii[i];
}
return arr;
}
public static void main(String[] args) throws IOException {
byte[] largeBytes = generateData();
String inStr = new String(largeBytes, StandardCharsets.UTF_8);
System.out.println(inStr.length());
System.out.println(inStr.substring(1_200_000_000));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment