You should use weakValues() if you need records whose values ββare poorly accessible for garbage collection. For example, when it might be useful ... let's say you have a class that allows users to add objects to it and save them as values ββin Map for any reason. This class is usually used as a singleton, so it will stick with your application for the whole time. However, the objects that the user adds to it are not necessarily so durable. The application will be executed with them long before its completion. You donβt want the user to manually remove these objects from his class when he 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 fine, ignoring your class) . The solution is to give a weakValues() map, and everything will work the way you want.
softValues() is good for caching ... if you have Map<Integer, Foo> and you want the entries to be deleted in response to the memory requirement, you would like to use it. You would not want to use weakKeys() or softKeys() , because both of them use the identifier == , which may cause problems for you (you will not be able to get the value with the key 300 , because the key that you are passing will probably not == key on the map).
source share