A friendly place for programming greenhorns!
Big Moose Saloon
Search
|
Java FAQ
|
Recent Topics
Register / Login
JavaRanch
»
Java Forums
»
Java
»
Beginning Java
Author
Collection: Understanding WeakHashMap
Barry Gaunt
Ranch Hand
Joined: Aug 03, 2002
Posts: 7729
posted
Sep 09, 2002 07:18:00
0
For the following example am I correct in saying that the assertion can fail,
because the
WeakHashMap
referenced by m2 could lose its contents, if there is some massive garbage collection taking place?
import java.util.*; class WHM { class K {} // object for creating keys public static void main(String[] args) { Map m1 = new HashMap(); Map m2 = new WeakHashMap(); // line 1 WHM w = new WHM(); K k1 = w.new K(); K k2 = w.new K(); m1.put(k1, "Item 1"); m2.put(k2, "Item 1"); // line 2 k1 = k2 = null; // line 3 /* * * * Later... assume that a massive garbage collection * is needed in this period * * */ Iterator i; i = m1.keySet().iterator(); while (i.hasNext()) { System.out.println((String)m1.get(i.next())); } assert !m2.isEmpty() : "m2 has lost it's contents"; // line 4 i = m2.keySet().iterator(); while (i.hasNext()) { System.out.println((String)m2.get(i.next())); } } }
Thanks
-Barry
Ask a Meaningful Question
and
HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Thomas Paul
mister krabs
Ranch Hand
Joined: May 05, 2000
Posts: 13974
posted
Sep 09, 2002 10:55:00
0
Yes. if the
WeakHashMap
contains the only reference to an object, then that object is eligible for GC.
Associate Instructor - Hofstra University
Amazon Top 750 reviewer
-
Blog - Unresolved References
-
Book Review Blog
I agree. Here's the link:
http://aspose.com/file-tools
subject: Collection: Understanding WeakHashMap
Similar Threads
Removing items in an iterator
Set issue.
MasterExam question
Generics
Instantiated interface Collection
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter