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 虚拟机内存占用。

从Bitmap.recycle说起

在Android中,Bitmap的存储分为两部分,一部分是Bitmap的数据,一部分是Bitmap的引用。

在Android2.3时代,Bitmap的引用是放在堆中的,而Bitmap的数据部分是放在栈中的,需要用户调用recycle方法手动进行内存回收,而在Android2.3之后,整个Bitmap,包括数据和引用,都放在了堆中,这样,整个Bitmap的回收就全部交给GC了,这个recycle方法就再也不需要使用了。

然而……

现在的SDK中对recycle方法是这样注释的,如图所示:

可以发现,系统建议你不要手动去调用,而是让GC来进行处理不再使用的Bitmap。我们可以认为,即使在Android2.3之后的版本中去调用recycle,系统也是会强制回收内存的,只是系统不建议这样做而已。

鄙司代码有些是从Android 2.3出来的,因此很多地方还在使用Bitmap.recycle。通常情况下,这也没什么问题,但是,今天遇到一个bug引发了Bitmap.recycle的血案。

起因

这个bug的起因是因为我们的一张图片需要旋转,同时可以设置一个旋转角度,老的代码是这样写的:

ImageView imageView = (ImageView) findViewById(R.id.test);
Matrix matrix = new Matrix();
matrix.setRotate(0.013558723994643297f);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
Bitmap targetBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
if (!bitmap.isRecycled()) {
    bitmap.recycle();
}
imageView.setImageBitmap(targetBmp);

除了中间的0.013558723994643297f这串比较奇葩的数据(当然,正常情况下都是20、30这样正常的数),其它都是比较正常的代码。

但实际上,只要一运行这段代码,程序就会崩溃,错误原因如下所示:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.xys.preferencetest, PID: 30512
    java.lang.RuntimeException: Canvas: trying to use a recycled bitmap android.graphics.Bitmap@1a50ff6b

这个问题一看就知道是由于Bitmap被调用recycle方法回收后,又调用了Bitmap的一些方法而导致的。可是,代码中可以发现我们recycle的是bitmap而不是通过Bitmap.createBitmap重新生成的targetBmp,为什么会报这个exception呢?

注释

按道理来说,bitmap与create出来的targetBmp应该是两个对象,当旋转角度正常的时候,确实也是这样,但当旋转角度比较奇葩的时候,这两个bitmap对象居然变成了同一个!而打开Bitmap.createBitmap的代码,可以发现如下所示的注释:

这里居然写着:The new bitmap may be the same object as source, or a copy may have been made.

看来还是真有可能为同一个对象的!

猜测

经过几次尝试,发现只有在角度很小很小的时候,才会出现这个情况,两个bitmap是同一个对象,因此,我只能这样猜测,当角度过小时,系统认为这是一张图片,没有发生变化,那么系统就直接引用同一个对象来进行操作,避免内存浪费。那么这个角度是怎么来的呢?继续猜测,如图所示:

当图像的旋转角度小余两个像素点之间的夹角时,图像即使选择也无法显示,因此,系统完全可以认为图像没有发生变化,因此,注释中的情况,是不是有可能就是说的这种情况呢?

注意,在 Bitmap 复用的时候,如果需要在同一个 Bitmap 中绘制其他内容的时候,需要先调用 eraseColor 进行图像擦除,如下:

/**
 * Fills the bitmap's pixels with the specified {@link Color}.
 *
 * @throws IllegalStateException if the bitmap is not mutable.
 */
 public void eraseColor(@ColorInt int c) {

另外图像擦除之后,再次调用绘制之前,需要调用 prepareToDraw 通知 GPU 对图像进行重新加载,否则可能会出现图像绘制错误,重叠,等各种问题。具体的解释参考如下:

/**
 * Builds caches associated with the bitmap that are used for drawing it.
 *
 * <p>Starting in {@link android.os.Build.VERSION_CODES#N}, this call initiates an asynchronous
 * upload to the GPU on RenderThread, if the Bitmap is not already uploaded. With Hardware
 * Acceleration, Bitmaps must be uploaded to the GPU in order to be rendered. This is done by
 * default the first time a Bitmap is drawn, but the process can take several milliseconds,
 * depending on the size of the Bitmap. Each time a Bitmap is modified and drawn again, it must
 * be re-uploaded.</p>
 *
 * <p>Calling this method in advance can save time in the first frame it's used. For example, it
 * is recommended to call this on an image decoding worker thread when a decoded Bitmap is about
 * to be displayed. It is recommended to make any pre-draw modifications to the Bitmap before
 * calling this method, so the cached, uploaded copy may be reused without re-uploading.</p>
 *
 * In {@link android.os.Build.VERSION_CODES#KITKAT} and below, for purgeable bitmaps, this call
 * would attempt to ensure that the pixels have been decoded.
 */
 public void prepareToDraw() {

参考链接


发布者

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注