1. 程式人生 > >android弱引用和軟應用的詳解

android弱引用和軟應用的詳解

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;