首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 軟引用 SoftReference 實戰:緩存設計與 Android 圖片加載優化

     編輯:Java 相關知識

SoftReference:「內存足夠不回收,內存不足才回收」,是實現內存敏感緩存的核心工具。

核心特性

  • GC 僅在 OutOfMemoryError 前回收軟引用對象
  • 獲取對象:ref.get() 返回強引用或 null(已被回收)
  • 典型模式:軟引用 + 失效重建

基礎使用模式

SoftReference ref = 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"); } }

Android 圖片緩存實戰

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) {
    // 重新解碼或從磁盤/網絡加載
}

權衡與避坑

進階建議

  • 大量圖片/大對象緩存 → LruCache (強引用) + DiskLruCache (磁盤) 多級策略
  • Android 3.0+ Bitmap 內存計入 Java 堆,軟引用效果更明顯
  • 避免在 finalize() 中復活對象,干擾 GC
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
優勢劣勢/風險
最大化內存利用,防 OOM對象初始化耗時長 → 重建延遲
自動適應內存壓力對象狀態易變 → 重建後狀態不一致
無需手動清理策略高併發下 get() 競態需同步