android弱引用和软应用的详解

来源:互联网 发布:社会网络下资产选择 编辑:程序博客网 时间:2024/06/06 03:43


Gc垃圾回收原理:当一个对象的被引用次数为0的时候很可能被回收

优化建议:

对占用内存大的对象:

在处理一些占用内存大而且声明周期较长的对象时候,可以尽量应用软引用和弱引用技术。

1.使用完就制空=null

2.主动调用一次gcsystem.gc();

几种引用:强、弱、软、虚

强应用(无法被gc回收)

String s=”abc”;(对abc的引用)

弱引用(强引用被制空null时就直接被gc回收)

急切回收

Counter counter = new Counter();// strong reference - line 1

WeakReference<Counter> weakCounter = new WeakReference<Counter>(counter);//weak reference

counter = null; // now Counter object is eligible for garbage collection

软引用:(当强应用对象被制空null也不会立即回收,除非需要)

缓存延迟

Counter prime = new Counter();// prime holds a strong reference – line 2

SoftReference soft = new SoftReference(prime) ;//soft reference variable has SoftReference to Counter Object created at line 2

 

prime = null; // now Counter object is eligible for garbage collection but only be collected when JVM absolutely needs memory

虚引用(可以在任何时候并gc回收)

DigitalCounter digit = new DigitalCounter();// digit reference variable has strong reference – line 3

PhantomReference phantom = new PhantomReference(digit);// phantom reference to object created at line 3

 

digit = null;

 

 

0 0