Strange behavior with weak references

  • Thread starter Nicholas Zigarovich
  • Start date
N

Nicholas Zigarovich

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");
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top