Skip to content

Instantly share code, notes, and snippets.

@untalfranfernandez
Last active January 4, 2016 19:49
Show Gist options
  • Save untalfranfernandez/8669472 to your computer and use it in GitHub Desktop.
Save untalfranfernandez/8669472 to your computer and use it in GitHub Desktop.
Testing OutOfMemoryError with StringBuilder.
@Test
public void shouldGetOutOfMemoryErrorUsingStringBufferButNotUsingStringWritter(){
int stringBuilderCapacity = 1024;
StringBuilder stringBuilder = new StringBuilder(stringBuilderCapacity);
String randomString = new BigInteger(stringBuilderCapacity++, new SecureRandom()).toString(32);
try {
while (true) {
stringBuilder.append(randomString);
stringBuilderCapacity *= 2;
}
} catch (OutOfMemoryError outOfMemoryError) {
StringWriter stringWriter = new StringWriter();
int stringWritterSize = 0;
while(stringWritterSize < stringBuilderCapacity){
stringWriter.write(randomString);
stringWritterSize += randomString.length();
}
assertTrue(stringWritterSize >= stringBuilderCapacity);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment