通過一個內存泄漏問題去再探探Handler源碼

有這樣一個場景:

public class MainActivity extends AppCompatActivity {
    private static final int DELAY_TIME = 1000 * 60 * 5;

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            //Todo-action
            return true;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = mHandler.obtainMessage();
                message.arg1 = 1;
                mHandler.sendMessageDelayed(message, DELAY_TIME);
            }
        }).start();
    }
}
如果當用戶進入當前Activity,並在DELAY_TIME 前退出activity,這個activity是不會被回收的。那麼產生內存泄漏的原因是什麼?我們不放先探一探源碼(個人隨筆免得忘記,有錯誤歡迎指正)。
我們知道Handler兩個主要作用1)、消息處理機制;2)多線程更新ui。那麼Handler是如何實現消息的傳遞以及線程的切換呢?帶着疑問我們去看下Handler類的構造函數(以在主線程中創建一個Handler默認構造函數爲例):
public Handler() {
    this(null, false);
}
public Handler(Callback callback, boolean async) {
    if (FIND_POTENTIAL_LEAKS) {
        final Class<? extends Handler> klass = getClass();
        if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                (klass.getModifiers() & Modifier.STATIC) == 0) {
            Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                klass.getCanonicalName());
        }
    }

    mLooper = Looper.myLooper();
    if (mLooper == null) {
        throw new RuntimeException(
            "Can't create handler inside thread that has not called Looper.prepare()");
    }
    mQueue = mLooper.mQueue;
    mCallback = callback;
    mAsynchronous = async;
}

從構造函數中看到兩個Handler的重要成員變量:Looper和MessageQueue的初始化。還發現Handler中的成員變量其實是Looper中的mQueue的引用,那Looper作用是什麼呢?來看下面這段話:
這個是關於Looper

* Class used to run a message loop for a thread. Threads by default do
* not have a message loop associated with them; to create one, call
* {@link #prepare} in the thread that is to run the loop, and then
* {@link #loop} to have it process messages until the loop is stopped.

源碼解釋寫的很清楚:Looper使用與爲一個線程循環的處理消息。我們不妨來看看 Looper.myLooper()做了啥
Looper.java:
public static @Nullable Looper myLooper() {
    return sThreadLocal.get();
}
ThreadLocal.java:
public T get() {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null) {
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null) {
            @SuppressWarnings("unchecked")
            T result = (T)e.value;
            return result;
        }
    }
    return setInitialValue();
}
ThreadLocalMap getMap(Thread t) {
    return t.threadLocals;
}

這個方法做的工作是找到當前的線程,拿到當前線程對應的Looper。那這時候就有疑問了,我們在Handler中並沒有做關於Looper的初始化,當前Looper的實力到底哪裏來呢,這時候再看Looper的註釋發現了這樣一個例子:
Looper.java:
* <pre>
*  class LooperThread extends Thread {
*      public Handler mHandler;
*
*      public void run() {
*          Looper.prepare();
*
*          mHandler = new Handler() {
*              public void handleMessage(Message msg) {
*                  // process incoming messages here
*              }
*          };
*
*          Looper.loop();
*      }
*  }</pre>

源碼給出了Looper的使用例子,從例子中看到了兩個關鍵的方法:Looper.prepare()和Looper.loop()。我們先來看下prepare():
Looper.java:
public static void prepare() {
    prepare(true);
}
private static void prepare(boolean quitAllowed) {
    if (sThreadLocal.get() != null) {
        throw new RuntimeException("Only one Looper may be created per thread");
    }
    sThreadLocal.set(new Looper(quitAllowed));
}
private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}
ThreadLocal.java:
public void set(T value) {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
}

咦,這好像是我們疑問的答案,prepare主要工作是創建一個Looper對象,並保存在當前線程對應的ThreadLocal中。但是,我們好像沒有找到有調用prepare()方法的地方啊,我們剛一直在提到一個詞-當前線程。我們再回到註釋給的例子,當前我們以主線程爲例,結合當前Handler所在線程ActivityThread,在ActivityThread中的main方法發現了這樣幾行代碼:
ActivityThread.java:
public static void main(String[] args) {
    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
    SamplingProfilerIntegration.start();

    // CloseGuard defaults to true and can be quite spammy.  We
    // disable it here, but selectively enable it later (via
    // StrictMode) on debug builds, but using DropBox, not logs.
    CloseGuard.setEnabled(false);

    Environment.initForCurrentUser();

    // Set the reporter for event logging in libcore
    EventLogger.setReporter(new EventLoggingReporter());

    // Make sure TrustedCertificateStore looks in the right place for CA certificates
    final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
    TrustedCertificateStore.setDefaultUserDirectory(configDir);

    Process.setArgV0("<pre-initialized>");

    Looper.prepareMainLooper();

    ActivityThread thread = new ActivityThread();
    thread.attach(false);

    if (sMainThreadHandler == null) {
        sMainThreadHandler = thread.getHandler();
    }

    if (false) {
        Looper.myLooper().setMessageLogging(new
                LogPrinter(Log.DEBUG, "ActivityThread"));
    }

    // End of event ActivityThreadMain.
    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
    Looper.loop();

    throw new RuntimeException("Main thread loop unexpectedly exited");
}

哈哈,get了,這就是我們要找的答案,在主線程中創建Handler,我們的Looper在Activity啓動階段已經被創建保存在當前線程的ThreadLocal中,已經對looper做了初始化。
搞明白了在哪裏調用prepare()和loop方法以及prepare()方法的主要工作,我們接下來看看loop()方法的主要工作,還是看一段源碼:
Looper.java:
/**
 * Run the message queue in this thread. Be sure to call
 * {@link #quit()} to end the loop.
 */
public static void loop() {
    final Looper me = myLooper();
    if (me == null) {
        throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
    }
    final MessageQueue queue = me.mQueue;

    // Make sure the identity of this thread is that of the local process,
    // and keep track of what that identity token actually is.
    Binder.clearCallingIdentity();
    final long ident = Binder.clearCallingIdentity();

    for (;;) {
        Message msg = queue.next(); // might block
        if (msg == null) {
            // No message indicates that the message queue is quitting.
            return;
        }

        // This must be in a local variable, in case a UI event sets the logger
        final Printer logging = me.mLogging;
        if (logging != null) {
            logging.println(">>>>> Dispatching to " + msg.target + " " +
                    msg.callback + ": " + msg.what);
        }

        final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

        final long traceTag = me.mTraceTag;
        if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
            Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
        }
        final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
        final long end;
        try {
            msg.target.dispatchMessage(msg);
            end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
        } finally {
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }
        if (slowDispatchThresholdMs > 0) {
            final long time = end - start;
            if (time > slowDispatchThresholdMs) {
                Slog.w(TAG, "Dispatch took " + time + "ms on "
                        + Thread.currentThread().getName() + ", h=" +
                        msg.target + " cb=" + msg.callback + " msg=" + msg.what);
            }
        }

        if (logging != null) {
            logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
        }

        // Make sure that during the course of dispatching the
        // identity of the thread wasn't corrupted.
        final long newIdent = Binder.clearCallingIdentity();
        if (ident != newIdent) {
            Log.wtf(TAG, "Thread identity changed from 0x"
                    + Long.toHexString(ident) + " to 0x"
                    + Long.toHexString(newIdent) + " while dispatching to "
                    + msg.target.getClass().getName() + " "
                    + msg.callback + " what=" + msg.what);
        }

        msg.recycleUnchecked();
    }
}

loop()方法其實就是個死循環,不斷的去遍歷當前成員變量mQueue,如果沒有消息就阻塞,如果有消息就循環對消息進行處理。在源碼中看到了比較中號的一行代碼:
msg.target.dispatchMessage(msg);
msg.target是什麼鬼??咦,它既然是個Handler類型,是不是發現什麼,來看看入口函數:
Handler.java:
public final boolean sendMessage(Message msg)
{
    return sendMessageDelayed(msg, 0);
}
....
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
    MessageQueue queue = mQueue;
    if (queue == null) {
        RuntimeException e = new RuntimeException(
                this + " sendMessageAtTime() called with no mQueue");
        Log.w("Looper", e.getMessage(), e);
        return false;
    }
    return enqueueMessage(queue, msg, uptimeMillis);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    msg.target = this;
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}
通過上面幾個方法我們找到想要的答案,target就是我們創建的Handler,msg.target.dispatchMessage(msg)自然是調用到Handler中的dispatchMessage()
public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        handleMessage(msg);
    }
}

在Handler中又調回了HandlerMessage()方法,這個方法很熟悉就不用介紹了吧。到這裏Looper的消息處理過程就大概講完了。不過還有點疑問,我們好像還不知道msg如何加入到Looper的隊列中哈
我們再從入口跟下消息的發佈過程:
Handler.java:
public final boolean sendMessage(Message msg)
{
    return sendMessageDelayed(msg, 0);
}
....
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
    MessageQueue queue = mQueue;
    if (queue == null) {
        RuntimeException e = new RuntimeException(
                this + " sendMessageAtTime() called with no mQueue");
        Log.w("Looper", e.getMessage(), e);
        return false;
    }
    return enqueueMessage(queue, msg, uptimeMillis);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    msg.target = this;
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
     return queue.enqueueMessage(msg, uptimeMillis);
}
MessageQueue.java
boolean enqueueMessage(Message msg, long when) {
    if (msg.target == null) {
        throw new IllegalArgumentException("Message must have a target.");
    }
    if (msg.isInUse()) {
        throw new IllegalStateException(msg + " This message is already in use.");
    }

    synchronized (this) {
        if (mQuitting) {
            IllegalStateException e = new IllegalStateException(
                    msg.target + " sending message to a Handler on a dead thread");
            Log.w(TAG, e.getMessage(), e);
            msg.recycle();
            return false;
        }

        msg.markInUse();
        msg.when = when;
        Message p = mMessages;
        boolean needWake;
        if (p == null || when == 0 || when < p.when) {
            // New head, wake up the event queue if blocked.
            msg.next = p;
            mMessages = msg;
            needWake = mBlocked;
        } else {
            // Inserted within the middle of the queue.  Usually we don't have to wake
            // up the event queue unless there is a barrier at the head of the queue
            // and the message is the earliest asynchronous message in the queue.
            needWake = mBlocked && p.target == null && msg.isAsynchronous();
            Message prev;
            for (;;) {
                prev = p;
                p = p.next;
                if (p == null || when < p.when) {
                    break;
                }
                if (needWake && p.isAsynchronous()) {
                    needWake = false;
                }
            }
            msg.next = p; // invariant: p == prev.next
            prev.next = msg;
        }

        // We can assume mPtr != 0 because mQuitting is false.
        if (needWake) {
            nativeWake(mPtr);
        }
    }
    return true;
}
通過上面可以看到,在調用Handler發佈一條消息其實就是往MessageQueue中根據特定規則加入一條消息,MessageQueue就是消息Msg的容器,looper中遍歷到消息來臨並對消息進行處理。
好了,在非主線程中,過程其實差不多,這裏重複分析。
流程走完了,再回到之前的那個問題--那麼產生內存泄漏的原因是什麼呢?
通過上面流程我們不難知道當前內存泄漏原因:
1)、通過匿名內部類創建Handler,當前Handler持有外部類的引用;
2)、又當前Handler被Msg持有在消息隊列中等待被Looper處理,Looper是ActivityThread持有的生命週期貫穿整個app的生命週期。
因此,如果上面這種情況,在activity突然退出,當前activity不會馬上被回收,會發生短暫的內存泄漏問題。
好像大部分時候我們都是這樣寫啊,那要怎麼改:
主要有兩個方法:
1)、將Handler聲明爲static內部類的方式;
2)、自己創建一個Looper,讓Looper保持和Handler所在類一樣的生命週期。
至此,終。
有問題歡迎指正~


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章