What are the benefits to using WeakReferences?

前端 未结 4 640
暗喜
暗喜 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 08:48

    The most straight-forward use of weak references I can think of is a cache. You want to add objects to a cache, but if there are no references to the object in the rest of the VM, you want the object to get GC'ed without having to go back and remove it from the cache yourself. Weak references achieve this. You add a weak reference to the object in your cache. When the cache is the only thing that refers to your object, it is eligible for GC. Attempts to use the weak reference after the object is GC'ed result in an exception.

    Strictly speaking, an object is eligible for GC when no strong references to it remain (i.e. whether or not any weak references to it exist).

    Based on your description of your situation, it is not clear that weak references will help you. But if you are facing a situation where you need to intentionally clear references to objects that are no longer needed, then weak references may be the solution. You just have to be sure that when only weak references remain, it really is OK to get rid of the object.

提交回复
热议问题