内存泄露了么: Handlers & Inner Classes
看到一篇关于handler和匿名类关于内存泄露的文章,觉得不错,充分发挥拿来主义,先放这儿看着!
Consider the following code:
public class SampleActivity extends Activity { private final Handler mLeakyHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// ...
}
}
}
While not readily obvious, this code can cause cause a massive memory leak. Android Lint will give the following warning:
In Android, Handler classes should be static or leaks might occur.
But where exactly is the leak and how might it happen? Let's determine the source of the problem by first documenting what we know:
When an Android application first starts, the framework creates a
Looper
object for the application's main thread. ALooper
implements a simple message queue, processingMessage
objects in a loop one after another. All major application framework events (such as Activity lifecycle method calls, button clicks, etc.) are contained insideMessage
objects, which are added to theLooper
's message queue and are processed one-by-one. The main thread'sLooper
exists throughout the application's lifecycle.When a
Handler
is instantiated on the main thread, it is associated with theLooper
's message queue. Messages posted to the message queue will hold a reference to theHandler
so that the framework can callHandler#handleMessage(Message)
when theLooper
eventually processes the message.In Java, non-static inner and anonymous classes hold an implicit reference to their outer class. Static inner classes, on the other hand, do not.
So where exactly is the memory leak? It's very subtle, but consider the following code as an example:
public class SampleActivity extends Activity { private final Handler mLeakyHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// ...
}
} @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Post a message and delay its execution for 10 minutes.
mLeakyHandler.postDelayed(new Runnable() {
@Override
public void run() { }
}, 60 * 10 * 1000); // Go back to the previous Activity.
finish();
}
}
When the activity is finished, the delayed message will continue to live in the main thread's message queue for 10 minutes before it is processed. The message holds a reference to the activity's Handler
, and the Handler
holds an implicit reference to its outer class (the SampleActivity
, in this case). This reference will persist until the message is processed, thus preventing the activity context from being garbage collected and leaking all of the application's resources. Note that the same is true with the anonymous Runnable class on line 15. Non-static instances of anonymous classes hold an implicit reference to their outer class, so the context will be leaked.
To fix the problem, subclass the Handler
in a new file or use a static inner class instead. Static inner classes do not hold an implicit reference to their outer class, so the activity will not be leaked. If you need to invoke the outer activity's methods from within the Handler
, have the Handler hold a WeakReference
to the activity so you don't accidentally leak a context. To fix the memory leak that occurs when we instantiate the anonymous Runnable class, we make the variable a static field of the class (since static instances of anonymous classes do not hold an implicit reference to their outer class):
public class SampleActivity extends Activity { /**
* Instances of static inner classes do not hold an implicit
* reference to their outer class.
*/
private static class MyHandler extends Handler {
private final WeakReference<SampleActivity> mActivity; public MyHandler(SampleActivity activity) {
mActivity = new WeakReference<SampleActivity>(activity);
} @Override
public void handleMessage(Message msg) {
SampleActivity activity = mActivity.get();
if (activity != null) {
// ...
}
}
} private final MyHandler mHandler = new MyHandler(this); /**
* Instances of anonymous classes do not hold an implicit
* reference to their outer class when they are "static".
*/
private static final Runnable sRunnable = new Runnable() {
@Override
public void run() { }
}; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Post a message and delay its execution for 10 minutes.
mHandler.postDelayed(sRunnable, 60 * 10 * 1000); // Go back to the previous Activity.
finish();
}
}
The difference between static and non-static inner classes is subtle, but is something every Android developer should understand. What's the bottom line? Avoid using non-static inner classes in an activity if instances of the inner class outlive the activity's lifecycle. Instead, prefer static inner classes and hold a weak reference to the activity inside.
内存泄露了么: Handlers & Inner Classes的更多相关文章
- JVM内存管理概述与android内存泄露分析
一.内存划分 将内存划分为六大部分,分别是PC寄存器.JAVA虚拟机栈.JAVA堆.方法区.运行时常量池以及本地方法栈. 1.PC寄存器(线程独有):全称是程序计数寄存器,它记载着每一个线程当前运行的 ...
- Android中Handler引起的内存泄露
在Android常用编程中,Handler在进行异步操作并处理返回结果时经常被使用.通常我们的代码会这样实现. 1 2 3 4 5 6 7 8 9 public class SampleActivit ...
- logging 模块误用导致的内存泄露
首先介绍下怎么发现的吧, 线上的项目日志是通过 logging 模块打到 syslog 里, 跑了一段时间后发现 syslog 的 UDP 连接超过了 8W, 没错是 8 W. 主要是 logging ...
- Android 中 Handler 引起的内存泄露
在Android常用编程中,Handler在进行异步操作并处理返回结果时经常被使用.其实这可能导致内存泄露,代码中哪里可能导致内存泄露,又是如何导致内存泄露的呢?那我们就慢慢分析一下.http://w ...
- 【转】内部Handler类引起内存泄露
如果您在Activity中定义了一个内部Handler类,如下代码: public class MainActivity extends Activity { private Handl ...
- Handler 引起的内存泄露
先看一组简单的代码 1 2 3 4 5 6 7 8 9 public class SampleActivity extends Activity { private final Handler mHa ...
- 【翻译】Android避免内存泄露(Activity的context 与Context.getApplicationContext)
原谅地址:http://android-developers.blogspot.com/2009/01/avoiding-memory-leaks.html ,英文原文在翻译之后 Android 应用 ...
- Activity内部Handler引起内存泄露的原因分析
有时在Activity中使用Handler时会提示一个内存泄漏的警告,代码通常如下: public class MainActivity extends Activity { private Text ...
- Java内存泄露监控工具:JVM监控工具介绍【转】
jstack?-- 如果java程序崩溃生成core文件,jstack工具可以用来获得core文件的java stack和native stack的信息,从而可以轻松地知道java程序是如何崩溃和在程 ...
随机推荐
- Mysql 数据分组取某字段值所有最大的记录行
需求: 表中同一个uid(用户)拥有多条游戏等级记录,现需要取所有用户最高等级(level)的那一条数据,且时间(time)越早排越前.这是典型的排名表 +------+-------+------- ...
- Linq to XML 之XElement的Descendants方法的新发现
C#操作XML的方法有很多,但个人认为最方便的莫过于Linq to XML了,特别是XElement的Descendants方法是我最常用的一个方法. 这个方法可以根据节点名(Name)找到当前调用的 ...
- [Android Training视频系列] 8.1 Controlling Your App’s Volume and Playback
主要内容:1 鉴别使用的是哪个音频流2 使用物理音量键控制应用程序的音量 3 使用物理播放控制键来控制应用程序的音频播放 视频讲解:http://www.eyeandroid.com/thread-1 ...
- 团队作业week2-软件分析和用户需求调查
我们的团队选择评定的软件是必应词典(iphone版)和使用较多的有道词典(iphone版) 类别 描述 评分(Bing) 评分(有道) 功能 核心功能1:词典 顾名思义,作为一款词典类 ...
- 团队项目之Sprint计划会议
一.我们团队在4月15日进行了冲刺计划会议,会议过程大致如下: 1.总结目前的工作进展,再一次确定所做项目的方向: 2.将之前的调查问卷的结果进行统计,做了需求分析,大致了解了用户的想法: 3.根据初 ...
- Problem 1016 咒文卷轴 优先队列+前缀和+rmq
题目链接: 题目 Problem 1016 咒文卷轴 Time Limit: 3000 mSec Memory Limit : 131072 KB 问题描述 小Y 是一个魔法师,有一天他获得了一卷神秘 ...
- 移动端页面使用rem来做适配
文/九彩拼盘(简书作者)原文链接:http://www.jianshu.com/p/eb05c775d3c6著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”. rem介绍 rem(font ...
- 【HDOJ】【4089】Activation
概率DP kuangbin总结中的第5题 题解copy: HDU 4098 题意:有n个人排队等着在官网上激活游戏.Tomato排在第m个. 对于队列中的第一个人.有一下情况: 1.激活失败,留在队列 ...
- C#动态多线程实例
在C#中用多线程并不难实现.它有一个命名空间:System.Threading,提供了多线程的支持. 要开启一个新线程,须要以下的初始化: ThreadStart startDownload = ne ...
- [设计模式] 19 观察者模式 Observer Pattern
在GOF的<设计模式:可复用面向对象软件的基础>一书中对观察者模式是这样说的:定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新.当一个 ...