garbage collection - How does HashMap in Java handle weak reference for keys and values? -


i read book java memory modelling, says : hashmap use weak reference keys , values(since objects), hashmap can avoid out of memory issue when hasnmap stores more , more key value pairs.

but problem : if keys , values being gc during rumtime, how can key value pair using get method in hashmap?

for example,

string key=new string("gc"); string value=new string("gc"); hashmap.put(key,value); 

and after execution of code, has chance java gc key , value, happen during:

hashmap.get(key) 

since key no longer exist in hashmap ?

it's weakhashmap, removes entries keys no longer referenced outside map itself. , happens after gc cleared key, here:

    map m = new weakhashmap();     m.put(new object(), 1);       // key referenced map     system.out.println(m.size()); // prints 1     system.gc();          thread.sleep(1); // give gc time     system.out.println(m.size()); // prints 0 

Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

order - Notification for user in user account opencart -