سؤال

While doing some researches about how to pass a object reference in android I was thinking about the following.

Let's assume I have a WeakHashmap with Long as keys. And now I put one Object into this WeakHashMap and assign it to the key 'new Long(1)' (assuming that I will save the reference to this Long).

Now another part of the application creates a new Long(1) and after that I set my first Long (that was used as key) to null.

  1. What would happen to the Object in the WeakHashMap?
  2. What if I replace Long with an own Class with a Long member and let its compare()-Method return true if its compared with another object of the same type (my own class) that has the same value in it's Long.
  3. Assuming that in both cases the WeakReference gets cleared. Would it make a difference if I use my second created key to access the WeakHasMap once before clearing the first on out?
هل كانت مفيدة؟

المحلول

A weak reference will be garbage collected when there are no strong references to the memory.

Now, your example. This a little tricky. From the javadoc for Long, the valueOf method improves performance by "caching frequently requested values". This means that it will make a difference to the answer whether you use valueOf or new.

In your case you use new so each new Long(1) will be a different object - i.e. a different reference. But this is something to bear in mind - Integer, Long and the other wrapper types are usually cached by the JVM may not behave as you expect in a WeakHashMap. Strings are interned so they are also problematic.

Anyway, to answer your questions:

  1. if there are no more strong references to you original Long then the mapping will be GC'ed at the next opportunity.
  2. I think you are confused here. A HashMap uses hashcode and equals for comparison. A TreeMap uses compareTo. In any case it would make no difference, this is about references not about any concept of equality. If there are no more strong references to your object then the mapping will be GC'ed.
  3. No it would not. As I said in 2. - the Map uses hashcode and equals when checking whether a key is already in the Map. The Weak part is talking about references. Two objects can be equals but not ==.

You can use a PhantomReference to track when your key is GC'ed. That might help you understand how weak references work.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top