Last active
October 5, 2018 19:14
-
-
Save corlaez/e1fc587ebc86a85ff612ed3a1b3e0a9a to your computer and use it in GitHub Desktop.
Understanding WeakMap with not interned Strings
This file contains hidden or 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
import java.util.WeakHashMap; | |
import java.lang.ref.WeakReference; | |
class Main { | |
public static void main(String[] args) { | |
WeakHashMap map = new WeakHashMap<String, Integer>(); | |
char[] arr = {'x'}; | |
String x = new String(arr); | |
String x2 = new String(arr); | |
boolean areEquals = x.equals(x2); | |
System.out.println("Not interned Strings equals? " | |
+ areEquals); | |
boolean sameRef = x == x2; | |
System.out.println("Not interned Strings ==? " | |
+ sameRef); | |
put(map); | |
gc(); | |
get(map); | |
} | |
// A method that sets a value to our map. The value is a not interned String | |
static void put(WeakHashMap map) { | |
char[] arr = {'x'}; | |
map.put(new String(arr), 5); | |
} | |
// A method that prints what our map holds right now | |
static void get(WeakHashMap map) { | |
System.out.println(map.entrySet()); | |
} | |
// A method that guaranties that gc runs, nice! | |
public static void gc() { | |
Object obj = new Object(); | |
WeakReference ref = new WeakReference<Object>(obj); | |
obj = null; | |
while(ref.get() != null) { | |
System.gc(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment