Android-Bitmap回收/复用机制

包括 recycle() 方法 bitmap 回收时机。

Android 系统版本的内存分配策略也有所不同,这是我们需要了解的:

系统版本 Bitmap 内存分配策略
Android 3.0 之前

Bitmap 对象存放在 Java Heap,而像素数据是存放在 native 内存中。

缺点:如果不手动调用 bitmap.recycle(),Bitmap native 内存的回收完全依赖 finalize() 回调,但是回调时机是不可控的

Android 3.0~7.0

Bitmap 对象和像素数据统一放到 Java Heap,即使不调用 bitmap.recycle(),Bitmap 像素也会随着对象一起被回收。

缺点:

1、Bitmap 全部放在 Java Heap,Bitmap 是内存消耗的大户,而 Max Heap 一般限制为 256、512MB,Bitmap 过大过多容易导致 OOM。

2、容易引起大量 GC,没有充分利用系统的可用内存

Android 8.0 及以后

1、使用了能够辅助回收 native 内存的 NativeAllocationRegistry 实现将像素数据放到 native 内存,并且可以和 Bitmap 对象一起快速释放,在 GC 的时候还可以考虑到这些 Bitmap 内存以防止被滥用。

2、新增硬件位图 Hardware Bitmap 解决图片内存占用过多和图像绘制效率过慢问题

手动调用recycle()

2.3 及以下版本,保存在 jvm + native 中,手动调用 recycle() 。

7.0 和 8.0 不需要调用 recycle(),下面是该版本下代码。

    /**
     * Free the native object associated with this bitmap, and clear the
     * reference to the pixel data. This will not free the pixel data synchronously;
     * it simply allows it to be garbage collected if there are no other references.
     * The bitmap is marked as "dead", meaning it will throw an exception if
     * getPixels() or setPixels() is called, and will draw nothing. This operation
     * cannot be reversed, so it should only be called if you are sure there are no
     * further uses for the bitmap. This is an advanced call, and normally need
     * not be called, since the normal GC process will free up this memory when
     * there are no more references to this bitmap.
     */
    //释放与此位图关联的本机对象,并清除对像素数据的引用。 这不会同步释放像素数据;
    //这是一个高级调用,通常不需要调用,因为当没有更多对此位图的引用时,正常的 GC 过程将释放此内存。
    public void recycle() {
        if (!mRecycled) {
            nativeRecycle(mNativePtr);
            mNinePatchChunk = null;
            mRecycled = true;
        }
    }
  
    private static native void nativeRecycle(long nativeBitmap);

7.0 跟 8.0 nativeRecycle 实现不同。

8.0 版本 Bitmap

static jboolean Bitmap_recycle(JNIEnv* env, jobject, jlong bitmapHandle) {
    LocalScopedBitmap bitmap(bitmapHandle);
    bitmap->freePixels();
    return JNI_TRUE;
}

void freePixels() {
    mInfo = mBitmap->info();
    mHasHardwareMipMap = mBitmap->hasHardwareMipMap();
    mAllocationSize = mBitmap->getAllocationByteCount();
    mRowBytes = mBitmap->rowBytes();
    mGenerationId = mBitmap->getGenerationID();
    mIsHardware = mBitmap->isHardware();
    //清空数据
    mBitmap.reset();
}

7.0 版本 Bitmap

static jboolean Bitmap_recycle(JNIEnv *env, jobject, jlong bitmapHandle) {
    LocalScopedBitmap bitmap(bitmapHandle);
    bitmap->freePixels();
    return JNI_TRUE;
}
//析构函数
Bitmap::~Bitmap() {
    doFreePixels();
}

void Bitmap::doFreePixels() {
    switch (mPixelStorageType) {
        //Invalid表示图片已经失效了,一般图片free掉之后就会是这种状态
        case PixelStorageType::Invalid:
            break;
        //外部存储
        case PixelStorageType::External:
            mPixelStorage.external.freeFunc(mPixelStorage.external.address,
                mPixelStorage.external.context);
            break;
        //匿名共享内存,Fresco 低版本内存优化,通过 BitmapFactory.Options.inPurgeable = true 
        //使得 bitmap 通过匿名共享内存方式保存
        case PixelStorageType::Ashmem:
            munmap(mPixelStorage.ashmem.address, mPixelStorage.ashmem.size);
            close(mPixelStorage.ashmem.fd);
            break;
        //java内存,主要看这种
        case PixelStorageType::Java:
            JNIEnv* env = jniEnv();
            LOG_ALWAYS_FATAL_IF(mPixelStorage.java.jstrongRef,
                "Deleting a bitmap wrapper while there are outstanding strong "
                "references! mPinnedRefCount = %d", mPinnedRefCount);
        //DeleteWeakGlobalRef 该函数删除一个弱全局引用,添加待删除的弱全局引用给 jvm
        env->DeleteWeakGlobalRef(mPixelStorage.java.jweakRef);
            break;
        }

        if (android::uirenderer::Caches::hasInstance()) {
            android::uirenderer::Caches::getInstance().textureCache.releaseTexture(
                mPixelRef->getStableID());
    }
}
  1. 8.0 中,手动调用 recycle() 方法,像素数据会立即释放;

  2. 7.0 版本中,调用 recycle() 方法像素数据不会立即释放,而是通过 DeleteWeakGlobalRef 交由 Jvm GC 处理。Java 层主动调用 recycle() 或者在 Bitmap 析构函数 freePixels() ,移除 Global 对象引用,这个对象是 Heap 内存一堆像素的空间。GC 时释放掉。二是 JNI 不再持有 Global Reference,并 native 函数执行后释放掉,但 Java 层的 Bitmap 对象还在,只是它的 mBuffer 和 mNativePtr 是无效地址,没有像素 Heap 的 Bitmap 也就几乎不消耗内存。Java 层 Bitmap 对象什么时候释放,生命周期结束自然会 free 掉。

回收机制

7.0 通过 java 层 BitmapFinalizer.finalize 实现,8.0 通过 native 层 NativeAllocationRegistry 实现。

7.0 及以下,保存在 jvm 虚拟机中,回收机制通过 BitmapFinalizer. finalize 实现。跟 BitmapFinalizer 而不跟 Bitmap 关联的原因是重写 finalize 方法的对象会被延迟回收,经过两次 gc 才会被回收。原因是重写 finalize 的对象在创建时会创建 FinalizerReference 并引用 Object,并将FR 关联到 ReferenceQueue 中,当第一次执行 gc 时候,会把 FR 放在 queue 中,其中有个守护线程持续读取 queue 中的数据,并执行 finalize 方法。

Bitmap(long nativeBitmap, byte[] buffer, int width, int height, int density,
            boolean isMutable, boolean requestPremultiplied,
            byte[] ninePatchChunk, NinePatchInsetStruct ninePatchInsets) {
        if (nativeBitmap == 0) {
            throw new RuntimeException("internal error: native bitmap is 0");
        }

        ...
        mNativePtr = nativeBitmap;
        // 这个对象对象来回收
        mFinalizer = new BitmapFinalizer(nativeBitmap);
        int nativeAllocationByteCount = (buffer == null ? getByteCount() : 0);
        mFinalizer.setNativeAllocationByteCount(nativeAllocationByteCount);
    }

    private static class BitmapFinalizer {
        private long mNativeBitmap;

        // Native memory allocated for the duration of the Bitmap,
        // if pixel data allocated into native memory, instead of java byte[]
        private int mNativeAllocationByteCount;

        BitmapFinalizer(long nativeBitmap) {
            mNativeBitmap = nativeBitmap;
        }

        public void setNativeAllocationByteCount(int nativeByteCount) {
            if (mNativeAllocationByteCount != 0) {
                //注销 native 内存
                VMRuntime.getRuntime().registerNativeFree(mNativeAllocationByteCount);
            }
            mNativeAllocationByteCount = nativeByteCount;
            if (mNativeAllocationByteCount != 0) {
                VMRuntime.getRuntime().registerNativeAllocation(mNativeAllocationByteCount);
            }
        }

        @Override
        public void finalize() {
            try {
                super.finalize();
            } catch (Throwable t) {
                // Ignore
            } finally {
                // finalize 这里是 GC 回收该对象时会调用
                setNativeAllocationByteCount(0);
                //本地析构函数,释放资源
                nativeDestructor(mNativeBitmap);
                mNativeBitmap = 0;
            }
        }
    }

    private static native void nativeDestructor(long nativeBitmap);

8.0 以上,保存在 jvm + native 中,NativeAllocationRegistry 中把 native 的文件描述符(句柄)跟 Cleaner 关联,Cleaner 其实是个虚应用,会在没有强应用关联的时候进行内存回收。

    // called from JNI
    Bitmap(long nativeBitmap, int width, int height, int density,
            boolean isMutable, boolean requestPremultiplied,
            byte[] ninePatchChunk, NinePatch.InsetStruct ninePatchInsets) {
        ...

        mNativePtr = nativeBitmap;
        long nativeSize = NATIVE_ALLOCATION_SIZE + getAllocationByteCount();
        //nativeGetNativeFinalizer() 方法传入 NativeAllocationRegistry
        NativeAllocationRegistry registry = new NativeAllocationRegistry(
                Bitmap.class.getClassLoader(), nativeGetNativeFinalizer(), nativeSize);
        //注册 Java 层对象引用与 native 层对象的地址
        registry.registerNativeAllocation(this, nativeBitmap);
    }

下面是 NativeAllocationRegistry.java 代码

public class NativeAllocationRegistry {

        private final ClassLoader classLoader;
        private final long freeFunction;
        private final long size;

        public NativeAllocationRegistry(ClassLoader classLoader, long freeFunction, long size) {
            ...
            //外部传入的 nativeGetNativeFinalizer ,有用
            this.freeFunction = freeFunction;
            this.size = size;
        }

        public Runnable registerNativeAllocation(Object referent, long nativePtr) {
            ...

            try {
                //注册 native 内存
                registerNativeAllocation(this.size);
            } catch (OutOfMemoryError oome) {
                applyFreeFunction(freeFunction, nativePtr);
                throw oome;
            }
            // Cleaner 绑定 Java 对象与回收函数
            Cleaner cleaner = Cleaner.create(referent, new CleanerThunk(nativePtr));
            return new CleanerRunner(cleaner);
        }


        private class CleanerThunk implements Runnable {
            private long nativePtr;

            public CleanerThunk(long nativePtr) {
                this.nativePtr = nativePtr;
            }

            public void run() {
                if (nativePtr != 0) {
                    //freeFunction 即为 nativeGetNativeFinalizer() 方法
                    applyFreeFunction(freeFunction, nativePtr);
                }
                registerNativeFree(size);
            }

        }

        private static class CleanerRunner implements Runnable {
            private final Cleaner cleaner;

            public CleanerRunner(Cleaner cleaner) {
                this.cleaner = cleaner;
            }

            public void run() {
                cleaner.clean();
            }
        }

        public static native void applyFreeFunction(long freeFunction, long nativePtr);
    }

NativeAllocationRegistry 内部是利用了 sun.misc.Cleaner.java 机制,简单来说:使用虚引用得知对象被GC的时机,在GC前执行额外的回收工作。

nativeGetNativeFinalizer()
// Bitmap.java
private static native long nativeGetNativeFinalizer();

// Bitmap.cpp
static jlong Bitmap_getNativeFinalizer(JNIEnv*, jobject) {
    // 转为long
    return static_cast<jlong>(reinterpret_cast<uintptr_t>(&Bitmap_destruct));
}

static void Bitmap_destruct(BitmapWrapper* bitmap) {
    delete bitmap;
}

nativeGetNativeFinalizer 是一个 native 函数,返回值是一个 long,这个值其实相当于 Bitmap_destruct() 函数的直接地址,Bitmap_destruct() 就是用来回收 native 层内存的。

故 NativeAllocationRegistry 利用虚引用感知 Java 对象被回收的时机,来回收 native 层内存;在 Android 8.0 (API 27) 之前,Android 通常使用Object#finalize() 调用时机来回收 native 层内存

Tips:Fresco 在 Android 4.4 及以下版本对 bitmap 内存做了优化,通过设置 BitmapFactory.Options.inPurgeable = true 使得 bitmap 保存在匿名共享内存中,减少了 Jvm 虚拟机内存占用。

继续阅读Android-Bitmap回收/复用机制