Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Java > Strange behavior with weak references

Reply
Thread Tools

Strange behavior with weak references

 
 
Nicholas Zigarovich
Guest
Posts: n/a
 
      09-02-2003
Hi folks,

Here's a code snippet showing some strange behavior with weak
references. We insert five strings (also tested with other types) into a
WeakHashMap, while keeping a reference to only the fifth string in a variable
called 'save'. The problem is, if we DO NOT set the value of 'save' to null
before assigning to it, the size of the WeakHashMap is reported as 0 at the
end of execution. If we DO set the value of 'save' to null before assigning to
it, the size of the WeakHashMap is reported as 1 at the end of execution. This
happens consistently over several dozen runs using Java 1.4.1_02 on Linux.

What gives? I can see no reason for this behavior. Any insight would be
appreciated.

Cheers,

-Nick

import java.util.*;

public class crap
{
public static void main (String a[])
{
// If save is NOT set to null, the WeakHashMap will have 0
// items at the end of the run. If save IS set to null, the
// WeakHashMap will have 1 item at the end of the run. WTF?
String save; //= null;

// build the map
WeakHashMap map = new WeakHashMap();
for (int i = 0; i < 10; i++)
{
String s = "a" + i;

// hold a reference to one of the strings we created so
// that it shouldn't be GC fodder later.
if (i == 5)
{
save = s;
}

map.put (s, new Integer(i));
}

// everything should still be in the map
checkMap ("BEFORE", map);

// try to force GC to occur
generateTrash ();

// at least 1 thing should be left in the map
checkMap ("AFTER", map);
}

private static void checkMap (String label, WeakHashMap map)
{
System.out.println (label + ": SIZE:" + map.size());
}


private static void generateTrash ()
{
ArrayList list = new ArrayList();
for (int i = 0; i < 1000000; i++)
{
list.add (new Integer(i));
}

System.out.println ("Took out trash");
}
}
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Weak/Soft references? Tegiri Nenashi Java 64 07-22-2008 02:52 PM
Can I convert Weak references to "hard" references ? Lars Willich Java 13 10-23-2007 07:49 PM
Problem with weak references on OS X 10.3 Caleb Clausen Ruby 7 02-06-2006 05:28 AM
What are Weak Unknown, Weak Zero and Weak 1? Kuan Zhou VHDL 1 01-24-2005 12:57 PM
Weak references - I must be missing something... Mark M Java 16 03-05-2004 05:31 PM



Advertisments
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57