I was reading up on weak references in java and sounds simple enough, if an object only has weak references on it, then it can be collected by the garbage collector. Except what happens if your reference becomes dead before you use the value?
Example:
Suppose I have a weak hashmap with the keys {1,2,3,4,5}, all with values of 1. Now suppose you have a random number generator for numbers in [1:10]. Now every time the number is gotten, it checks if it a key in the map and then gives a temporary strong reference to the key. So with this setup, you'll have some keys having strong references and thus stay in memory, but you also have the probability that some keys will become dead before being chosen.
If my intuition for weak hashmaps is correct, does that mean that the map will at some point be altered from its original state?
Trying to use
Integerobjects as keys for aWeakHashMapis likely to result in some strange behavior. To start with, the javadoc forWeakHashMaphas the following note:Consider the following code:
The loop will start by printing "OVER 9000!?", but after the first loop, the original key has been discarded (even if there's now a reference to a key that is
equalsto it). As a result, if that key object gets garbage collected, the entry will be removed from the map and the loop will begin printing "null" instead. Since we callSystem.gc();after discarding the key, it's likely that this happens after a single loop.That's not the end of the issues with using
Integeras aWeakHashMapkey, though. If you change the value 9001 above to 1, you'll find that the behavior changes! (Probably? This may be implementation-dependent.) Now, the entry never gets removed from the map. This is because of the integer cache--Integer.valueOf(1)always returns the sameIntegerinstance, butInteger.valueOf(9001)creates a newIntegerinstance each time.This second issue is specific to
Integer, but the first actually applies to any scheme where you try to use keys whereequalsis not based on==. And ifequalsis based on==, then your question doesn't really apply--if you don't have a strong reference to the key anymore, it doesn't matter whether the value gets removed from the map because you no longer have a way to get to it--you can't recreate a key that uses identity-based equality.