When a entry in a map has weak key reference, the entry will be removed at the next garbage collection, right?
I can understand that the MapMaker
class provides the weakKeys
method. But I am confused with the weakValue()
. when should I use weakValue
or softValue
in MapMaker
?
You'd use weakValues()
when you want entries whose values are weakly reachable to be garbage collected. For an example of when this might be useful... say you have a class that allows users to add objects to it and stores them as values in a Map
for whatever reason. This class is typically used as a singleton, so it'll stick around the whole time your application is running. However, the objects the user adds to it aren't necessarily so long-lived. The application will be done with them long before it finishes. You don't want the user to have to manually remove these objects from your class when it is finished with them, but you don't want a memory leak by keeping references to them in your class forever (in other words garbage collection should just work like normal, ignoring your class). The solution is to give the map weakValues()
and everything will work as you want.
softValues()
is good for caching... if you have a Map<Integer, Foo>
and you want entries to to be removable in response to memory demand, you'd want to use it. You wouldn't want to use weakKeys()
or softKeys()
because they both use ==
identity, which would cause problems for you (wouldn't be able to get a value with key 300
out because the key you pass in probably wouldn't ==
the key in the map).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With