Strange behavior with weak references

Discussion in 'Java' started by Nicholas Zigarovich, Sep 2, 2003.

  1. 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");
    }
    }
     
    Nicholas Zigarovich, Sep 2, 2003
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Kuan Zhou
    Replies:
    1
    Views:
    5,202
    Paul Uiterlinden
    Jan 24, 2005
  2. Mark M
    Replies:
    16
    Views:
    738
    Chris Uppal
    Mar 5, 2004
  3. Lars Willich
    Replies:
    13
    Views:
    911
    Ian Shef
    Oct 23, 2007
  4. Tegiri Nenashi

    Weak/Soft references?

    Tegiri Nenashi, Jul 9, 2008, in forum: Java
    Replies:
    64
    Views:
    1,832
    Tom Anderson
    Jul 22, 2008
  5. Caleb Clausen
    Replies:
    7
    Views:
    178
    Logan Capaldo
    Feb 6, 2006
Loading...

Share This Page