When should you use weakValues ​​() of the MapMaker class?

When the record on the card has a weak key link, the record will be deleted in the next garbage collection, right?

I understand that the MapMaker class provides a weakKeys method. But I'm confused with weakValue() . When should I use weakValue or softValue in MapMaker ?

+4
source share
1 answer

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).

+3
source

Source: https://habr.com/ru/post/1344386/


All Articles