Android Message内存泄漏问题

    xiaoxiao2021-03-25  159

    在Android 4.1以上SDK中Message类的回收修复之前的内存泄漏bug

    在Android 4.4版本的Message类回收函数实现如下:

      /**      * Return a Message instance to the global pool.  You MUST NOT touch      * the Message after calling this function -- it has effectively been      * freed.      */     public void recycle() {         clearForRecycle();         synchronized (sPoolSync) {             if (sPoolSize < MAX_POOL_SIZE) {                 next = sPool;                 sPool = this;                 sPoolSize++;             }         }     }

    在Android 6.0版本中Message类的回收函数实现如下:

    public void recycle() { if (isInUse()) { if (gCheckRecycle) { throw new IllegalStateException("This message cannot be recycled because it " + "is still in use."); } return; } recycleUnchecked(); } /** * Recycles a Message that may be in-use. * Used internally by the MessageQueue and Looper when disposing of queued Messages. */ void recycleUnchecked() { // Mark the message as in use while it remains in the recycled object pool. // Clear out all other details. flags = FLAG_IN_USE; what = 0; arg1 = 0; arg2 = 0; obj = null; replyTo = null; sendingUid = -1; when = 0; target = null; callback = null; data = null; synchronized (sPoolSync) { if (sPoolSize < MAX_POOL_SIZE) { next = sPool; sPool = this; sPoolSize++; } } }

    在recycle()增加isInUse正在使用的异常判断,防止显示调用时释放还在用的Message对象。

    尽管在程序中使用Message.obtain()方法,一般情况下无需显示调用recycle,在Handler的Looper中会对用完msg进行回收的。

    msg.recycleUnchecked();

    转载请注明原文地址: https://ju.6miu.com/read-4431.html

    最新回复(0)