Android 静态变量不可信

引语
  • 在以前公司上看过一篇文章,大概是说 Pony 跟朋友的聊天消息乱码,初始还以为他们在用潮汕话聊呢(开玩笑的),按常规逻辑很难想明白,然后根据 Android 不可信的思路,终于顺利找到原因,具体忘了是什么原理,大概是存取结果不一致之类的吧。
  • 最近有在思考,写一个方法的时候,怎么知道将会在主线程还是非主线程运行的呢?后面想到,应该是有“不可信”的原则,即不要相信外面调用的方法所在的线程。

有一个 NullPointerException 的报错,一直想不明白,明明都已经赋值了,却还会报错。
Android 应该会在它认为需要的时候回收内存,包括 Static 变量,然后被使用时,再自动初始化,但初始化是根据类初始声明来的,所以后面有赋值的,不一定会保证一直都有。
这里应该是 static 变量被回收,然后再初始化,就没值了。
故应该多给自己一个思想:Static 变量不可信,使用时要先判断。

另外也需要注意,静态变量有时会一直占用内存,导致性能变差。
所以一方面,要防止它没了,一方面,又注意它一直都在的问题。
参考:
不解
发现在自己做事件中心,或者是 activty manage 时,都会定义类似

public staitc final List xxx = new List..

的代码,这个看起来也没什么更好的办法;
那么问题来了,系统什么时候会回收这个 list 的内容呢?

我现在的理解是:只要程序没被kill 掉或者 crash ,那里的内容就不会被回收。

有 staticOverflow 找到两个类似但又不完全一样的解答:
一:

Static variables are associated with a class and they will live as long as the class is in the memory,and destroy when class gets unloaded (which very rarely happens). It can happen when-

 -You force stop your app.
 -Application crashes.
 -You clear your app data.
 -Switch off your Device(Shutdown DVM).

二:

Lets start with a bit of background: What happens when you start an application?
The OS starts a process and assigns it a unique process id and allocates a process table.A process start an instance of DVM(Dalvik VM); Each application runs inside a DVM.
A DVM manages class loading unloading, instance lifecycle, GC etc.

Lifetime of a static variable: A static variable comes into existence when a class is loaded by the JVM and dies when the class is unloaded.

So if you create an android application and initialize a static variable, it will remain in the JVM until one of the following happens:
1. the class is unloaded
2. the JVM shuts down
3. the process dies

Note that the value of the static variable will persist when you switch to a different activity of another application and none of the above three happens. Should any of the above three happen the static will lose its value.

You can test this with a few lines of code:

  1. print the uninitialized static in onCreate of your activity -> should print null
  2. initialize the static. print it -> value would be non null
  3. Hit the back button and go to home screen. Note: Home screen is another activity.
  4. Launch your activity again -> the static variable will be non-null
  5. Kill your application process from DDMS(stop button in the devices window).
  6. Restart your activity -> the static will have null value.

Hope that helps.

来自: http://stackoverflow.com/questions/1944369/android-static-object-lifecycle-application-act-crazy/1944564#1944564

我在两个论坛也发帖提问了:















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值