Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Why is my weak reference returning null? Turing award for an answer :P

1059726Dec 11 2013 — edited Dec 13 2013

From the code posted below.  In the main method, the first println, it will print "x" object.  However, the object passed in the second println is an rval object and it *consistently* returns null.  Note, I've tried switching the two print's around and it the result is unchanged.  I guess I was under the opinion that explicit binding to x' and being on the stack as a temporary variable would be considered strong and *both* should return the object passed to the "method" method.  But yet, it gets lost in one instance.  I was also thinking that "method"'s "o" parameter would be considered strong as well.  I tried dumping as much to the sys.out to make sure nothing is being optimized away.

Why does my weak reference return null when - apparently to me - there *are* strong references?  Is it possible the gc would collect collect the referent if there is not enough memory - despite have a strong reference elsewhere?  Wouldn't seem like it.  Is it possible and how would you rewrite the following code to *guarantee* that the weak reference will never return null?  Maybe soft reference is what I'm looking for?  I just want it under no circumstance *ever* (translate guarantee), even when memory is tight & the gc is working hard, that I lose the referent if there is a strong reference.

Thanks

______________________________________________

public class Main {

    static Object method(final Object o) {

        final WeakReference wr = new WeakReference(o);

        final List<Integer> list = new ArrayList();

        for (int i = 0; i < 100000; ++i) {

            list.add(i);

            if (i % 1000 == 0) {

                System.gc();

            }

        }

        int total = 0;

        for (final int i : list) {

            total += i;

        }

        System.out.println(total);

        return wr.get();

    }

    public static void main(final String[] args) throws Exception {

        final Object x = new Object();

        System.out.println(method(x));

        System.out.println(method(new Object()));

    }

}

Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 10 2014
Added on Dec 11 2013
6 comments
3,186 views