SoftReference:「內存足夠不回收,內存不足才回收」,是實現內存敏感緩存的核心工具。
OutOfMemoryError 前回收軟引用對象ref.get() 返回強引用或 null(已被回收)SoftReferenceref = new SoftReference<>(new SomeObject()); // 使用時 SomeObject obj = ref.get(); if (obj == null) { obj = new SomeObject(); // 重建 ref = new SoftReference<>(obj); }
public class SoftReferenceDemo {
public static void main(String[] args) {
A a = new A();
a.test();
SoftReference sr = new SoftReference<>(a);
a = null; // 釋放強引用
// 下次使用
if (sr != null) {
a = sr.get();
if (a != null) a.test();
else { a = new A(); a.test(); sr = new SoftReference<>(a); }
}
}
}
class A { public void test() { System.out.println("Soft Reference test"); } }
Map> imageCache = new HashMap<>(); // 存入 Bitmap bitmap = BitmapFactory.decodeStream(inputStream); SoftReference softRef = new SoftReference<>(bitmap); imageCache.put("key1", softRef); // 取出 SoftReference cachedRef = imageCache.get("key1"); Bitmap bitmap = cachedRef.get(); // 可能為 null if (bitmap == null) { // 重新解碼或從磁盤/網絡加載 }
| 優勢 | 劣勢/風險 |
|---|---|
| 最大化內存利用,防 OOM | 對象初始化耗時長 → 重建延遲 |
| 自動適應內存壓力 | 對象狀態易變 → 重建後狀態不一致 |
| 無需手動清理策略 | 高併發下 get() 競態需同步 |