Skip to content

Instantly share code, notes, and snippets.

@misTrasteos
Last active December 8, 2021 00:12
Show Gist options
  • Save misTrasteos/152b8af569cdf9e8aace330a8ed60902 to your computer and use it in GitHub Desktop.
Save misTrasteos/152b8af569cdf9e8aace330a8ed60902 to your computer and use it in GitHub Desktop.
WeakHashMap JVM Java Example
///usr/bin/env jbang "$0" "$@" ; exit $?
//JAVA_OPTIONS -Xms32m -Xmx32m -Xlog:gc* -XX:+UseSerialGC
/// -XX:+HeapDumpBeforeFullGC
/// jbang run -D=WEAK WeakHashMapPoc.java for infinite execution as weak references are collected before an OOO
/// jbang run -D=STRONG -D=WEAK WeakHashMapPoc.java OOO even using a WeakHashMap, as keys are strongly referenced
/// jbang run WeakHashMapPoc.java for an OOO as simple Map keys are strongly referenced
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Random;
import java.util.WeakHashMap;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
public class WeakHashMapPoc {
private static Function<Integer, String> getRandomString = (size) -> {
byte[] array = new byte[size];
new Random().nextBytes(array);
return new String(array, StandardCharsets.UTF_8);
};
public static void main(String... args) {
Map<String, String> map = null;
if( System.getProperty("WEAK") != null)
map = new WeakHashMap<String, String>();
else
map = new HashMap<String, String>();
// strong references to the keys
List<String> keys = new ArrayList<String>();
while( Boolean.TRUE ) {
String key = getRandomString.apply(1_000);
map.put(key, getRandomString.apply(1_000));
if( System.getProperty("STRONG") != null)
// a strong reference to the key is being held here
// the weak hash map will never free the memory
// an OOO will eventually happen
keys.add( key );
//System.out.println( map.size() ); // some debug output
}//while
}//main
}//class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment