What are the benefits to using WeakReferences?

前端 未结 4 630
暗喜
暗喜 2020-12-25 08:21

I have some memory leaks in my app. They all originate around a specific view cluster that I have spent a loooot of time tweaking and trying to reduce a much contextual pass

4条回答
  •  天命终不由人
    2020-12-25 09:04

    A need for WeakReferences comes from a scenario in which you need to maintain metadata about an object for which you do not control.

    A contrived example would be String, it is final, and we cannot extend it, but if we would like to maintain some extra data about a specific String instance, we would likely use a Map implementation that would hold this metadata. For this example, I will suggest we want to keep the length of the string as our metadata (yes I know that the String object already has a public length property). So we would create a Map like this:

    Map stringLengths = new HashMap();
    

    Assume that we might populate this map in some method, and not know when we are done with the data, so we cannot explicitly remove the entries. As we populate this map, which will never be unpopulated, our references will be held onto forever. If the application runs for a long time, there is a good chance that we will run into an OutOfMemoryError.

    A solution to this would be to use a WeakHashMap implementation.

    Map stringLengths = new WeakHashMap();
    

    This way, when all (strong) references to the key are gone, the next GC will cause the entry of the WeakHashMap to be removed. (Yes, I understand that String has a special place in the heart of the JVM, but I am assuming that String's are GC'd the same way a normal Object would be in this contrived example)

    If this is the approach you are using in your app (storing your Bitmaps in a global map), I think this is definitely something to look into.

提交回复
热议问题