Skip to content

Instantly share code, notes, and snippets.

@misTrasteos
Last active December 29, 2021 22:30
Show Gist options
  • Save misTrasteos/9e7c3b2fc0aa3eec5291b669beec9479 to your computer and use it in GitHub Desktop.
Save misTrasteos/9e7c3b2fc0aa3eec5291b669beec9479 to your computer and use it in GitHub Desktop.
Simple Memory Leak in Java
///usr/bin/env jbang "$0" "$@" ; exit $?
//DEPS org.apache.commons:commons-lang3:3.12.0
//JAVA_OPTIONS -XX:-UseAdaptiveSizePolicy
//JAVA_OPTIONS -Xms16m -Xmx16m
//JAVA_OPTIONS -XX:NewSize=3m -XX:MaxNewSize=3m -XX:SurvivorRatio=1
//JAVA_OPTIONS -XX:MaxTenuringThreshold=5
//JAVA_OPTIONS -Xlog:gc*
//JAVA_OPTIONS -XX:+UseSerialGC
//JAVA_OPTIONS -XX:+HeapDumpOnOutOfMemoryError
import java.util.List;
import java.util.LinkedList;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
public class AnotherMemoryLeak {
public static void main(String... args) {
List<String> strings = new LinkedList<String>();
int elementsToAdd = 1_000;
int elementsToRemove = 900;
while( args.length >= 0) {
for(int i=0; i<elementsToAdd; i++)
strings.add( RandomStringUtils.randomAlphanumeric( 1_000 ) );
for(int i=0; i<elementsToRemove; i++)
if( strings.size() > 0 )
strings.remove( RandomUtils.nextInt(0, strings.size()) );
}
System.out.println( strings.size() );
}
}
///usr/bin/env jbang "$0" "$@" ; exit $?
//DEPS org.apache.commons:commons-lang3:3.12.0
//JAVA_OPTIONS -Xms2g -Xmx2g
//JAVA_OPTIONS -Xlog:gc*
//JAVA_OPTIONS -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC
//JAVA_OPTIONS -XX:+HeapDumpOnOutOfMemoryError
import java.util.List;
import java.util.ArrayList;
import org.apache.commons.lang3.RandomStringUtils;
public class MemoryLeak {
List<String> listOfGarbage = new ArrayList<String>();
private void doStuff() throws Exception {
while(true){
Thread.sleep(100);
listOfGarbage.add( RandomStringUtils.randomAlphanumeric( 1_000 ) );
}
}
public static void main(String... args) throws Exception {
new MemoryLeak().doStuff();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment