内存泄露了么: 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程序是如何崩溃和在程 ...
随机推荐
- 你的数据根本不够大,别老扯什么Hadoop了
本文原名"Don't use Hadoop when your data isn't that big ",出自有着多年从业经验的数据科学家Chris Stucchio,纽约大学柯 ...
- python之量的概念
程序设计语言: 量的类型: 1. 直接量 2. 常量 3. 变量 量的因素: 1. 存储类别 2. 数据类型 3. 作用域 4. 生存期
- Pomodairo,番茄工作法-解刨篇
处于“信息大爆炸”的 e 时代的我们每天必定要处理很多的事情,不管是工作.学习.生活......面对这么多的纷杂的事物我们将如何应对?如何做到有条不紊的进行?高效.轻松.愉快的完成它呢?这时一款精致的 ...
- centos nginx,php添加到Service
SHELL脚本: nginx vim /etc/init.d/nginx #!/bin/sh # # nginx - this script starts and stops the nginx da ...
- POJ 3723 Conscription 最小生成树
题目链接: 题目 Conscription Time Limit: 1000MS Memory Limit: 65536K 问题描述 Windy has a country, and he wants ...
- sysconf和pathconf使用
问题描述: 查看系统运行时的限制值 问题解决: 执行效果: 源代码:
- 【BZOJ】【2693】JZPTAB
莫比乌斯反演 PoPoQQQ讲义第5题,是BZOJ 2154的升级版(多次询问) 题解:http://blog.csdn.net/popoqqq/article/details/42078725 WA ...
- Java多线程——<三>简单的线程执行:Executor
一.概述 按照<Java多线程——<一><二>>中所讲,我们要使用线程,目前都是显示的声明Thread,并调用其start()方法.多线程并行,明显我们需要声明多个 ...
- windows下几种I/O端口(了解)
如果你想在Windows平台上构建服务器应用,那么I/O模型是你必须考虑的.Windows操作系统提供了选择(Select).异步选择(WSAAsyncSelect).事件选择(WSAEventSel ...
- ASP文件操作(FSO)详解
实例一:写入文件 语法 object.CreateTextFile([要建立的文件],[如存在,是否替代]) <% Set fs =Server.CreateObject("Scrip ...