我应该担心内存泄漏和使用的WeakReference与凌空机器人

问题描述:

在阅读这篇文章,我开始思考与凌空内存泄漏。 通常情况下,用排枪实施听众要么是隐性或显性引用外部类(活动)。例如:

After reading this article, I started thinking about memory leaks with Volley. Usually, the listeners implemented with Volley have either an implicit or explicit reference to the outer class (the activity). for example:

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
        url, null, 
        new Response.Listener<JSONObject>() {
            @Override 
            public void onResponse(JSONObject response) {

                updateLayout(); 
            } 
        }

在这种情况下,有一个隐含的参考...或者我可能希望创建一个自定义JsonObjectRequest内化响应处理,并需要传递一个参考它的构造函数调用的活动。

in this case there is an implicit reference... or I may want to create a custom JsonObjectRequest to internalize the response handling, and need to pass in a reference to the calling activity in its constructor.

现在可以说,我开始一个Web请求,但在此之前的反应回来,我导航离开该开始请求的活动。从我了解的JsonObjectRequest对象将保持引用到我的活动和prevent它被垃圾收集。
-Am我正确认识这一点,这是一个合法的恐惧?
-Does凌空库会自动处理这个?
- 如果正在创建一个自定义JsonObjectRequest和传递一个本(参考活动),我需要创建一个WeakReference的的活动呢?

Now lets say I start a web request, but before the response comes back, I navigate away from the activity that started the request. From what I understand the JsonObjectRequest object would keep a reference to my activity and prevent it from being Garbage collected.
-Am I understanding this correctly, is this a legitimate fear?
-Does the Volley library automatically deal with this?
-If am creating a custom JsonObjectRequest and passing in a "this" (reference to activity), do I need to create a WeakReference to the activity?

根据望着凌空code,呼吁取消并没有真正避免了内存泄漏,因为引用永远不会被清零,并且引用不是弱。呼叫取消既避免抽射交付回应听众。

Based on looking at the volley code, calling cancel doesn't really avoid the memory leak because the reference never gets cleared and the reference isn't weak. Calling cancel only avoids Volley from delivering the response to the listener.

我解决这个问题就必须要克隆和修改图书馆自己。

My solution to the problem would have to be cloning and modifying the library myself.

  • 解决的办法之一可以使基地ErrorListener参考基准Request.java内是弱引用。而同样同样可以JsonRequest.java内进行的监听器。

  • One of the solutions can be to make base ErrorListener reference inside of base Request.java to be weak reference. And similarly the same can be done to the Listener inside of JsonRequest.java.

其他的解决方案,可以手动清除取消后,被称为参考。内取消(),设置mErrorListener和mListener为null。有了这个解决方案,但是,你必须删除从现场申报,否则你将不会被允许设置参考为null final修饰符。

The other solution can be to manually clear the reference upon cancel being called. inside of cancel(), set the mErrorListener and mListener to null. With this solution though, you'll have to remove the final modifier from the field declaration otherwise you wouldn't be allowed to set the reference to null.

希望这有助于。