Last active
January 4, 2016 19:49
-
-
Save untalfranfernandez/8669472 to your computer and use it in GitHub Desktop.
Testing OutOfMemoryError with StringBuilder.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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