android Message机制详解

最近被问到Message池最多有多少个?瞬间懵逼了。是该好好来了解下Message机制了。


Message源码就不贴了,自己点开看下就好。

一般滴,我们是这么用的:

Message msg = Message.obtain();
msg.what = MSG_SHOP;
msg.obj = bean;
handler.sendMessage(msg);

为啥这么用呢?人家官网说了:

While the constructor of Message is public, the best way to get
* one of these is to call {@link #obtain Message.obtain()} or one of the
* {@link Handler#obtainMessage Handler.obtainMessage()} methods, which will pull
* them from a pool of recycled objects.

虽然Message提供了一个公共方法来共造实例,但是最好的方式是调用Message.obtain()来获取,因为当它被回收时会被放入一个对象池中。

public static Message obtain() {
    synchronized (sPoolSync) {
        if (sPool != null) {
            Message m = sPool;
            sPool = m.next;
            m.next = null;
            m.flags = 0; // clear in-use flag
            sPoolSize--;
            return m;
        }
    }
    return new Message();
}
obtain()方法我们发现,确实有一个sPool的对象:

private static final Object sPoolSync = new Object(); // 线程锁
private static Message sPool; // 静态消息
private static int sPoolSize = 0; // 当前可用消息池个数

private static final int MAX_POOL_SIZE = 50; // 最大Message数量

private static boolean gCheckRecycle = true;
终于知道Message消息最大个数是多少了 MAX_POOL_SIZE=50;

next保存的是下一个可以使用的Message对象,当sPool被使用后,sPool将会指向next,而next被置null,这不就是数据结构中的一个链表吗?也就是说Message池是通过一个链表来实现的!

当第一次调用Mesage.obtain()方法时,sPool肯定是null,所以会new一个Message对象,所以obtain()方法是不会返回为null的,放心使用。

sPool!= null时,这个时候使用的就是Message池的链表头sPool对象了,然后sPool指向下一个next消息,可用Message数量减一,同时设置message使用标志。

那缓存池中的Message对象是什么时候存入的呢?上代码:

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++;
        }
    }
}
该方法是当Message不被使用时进行回收的代码。

当sPoolSize可用Message数量小于最大Message数量50时,就将当前的sPool对象指向下一个next对象,而sPool对象则保存当前的Message对象,sPoolSize再加一。

也就是说,当我们需要获取Message消息时,拿到的是链表头sPool对象;存储时,也是从链表头sPool存储的。即相当于一个Message栈,进出都是最后入栈的Message。

recycleUnchecked()方法是什么时候调用的呢?

public void recycle() {
    if (isInUse()) {
        if (gCheckRecycle) {
            throw new IllegalStateException("This message cannot be recycled because it "
                    + "is still in use.");
        }
        return;
    }
    recycleUnchecked();
}
recycle()回收方法,当Message没有使用后,将进行回收。还记得我们的Looper类吗?

这个就得去分析Looper类了,我们知道在创建Handler前必须调用Looper.prepare()方法,来实例化一个Looper对象。

而在Looper中维持着一个消息循环:

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 traceTag = me.mTraceTag;
    if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
        Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
    }
    try {
        msg.target.dispatchMessage(msg);
    } finally {
        if (traceTag != 0) {
            Trace.traceEnd(traceTag);
        }
    }

    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();
}

不停的从messageQueue队列中读取消息,当有消息后进行消息分发,最后在调用msg.recycleUnchecked();方法,对Message消息进行回收,这不就是我们上面说的回收方法吗?

所以,Message池是通过链表方式进行缓存的,读取和存入都是在链表头sPool。最大Message数是50!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值