Handler系列-Message是怎么重复利用的

1.Message类的支持

  • 使用链表来缓存Message,sPool为表头;
  • 最多能缓存50个Message;
  • sPoolSync用来保证读写链表的安全;
public final class Message implements Parcelable {
    private static Message sPool; //缓存的列表表头
    /*package*/ Message next;
    private static final Object sPoolSync = new Object();
    
    private static int sPoolSize = 0;//当前缓存的Message的个数

    private static final int MAX_POOL_SIZE = 50; //最多只能缓存50个Message
}

 2.获得消息

  • 返回表头的Message,将下一个消息更新为新的表头;
public final class Message implements Parcelable {
    public static Message obtain() {
        synchronized (sPoolSync) {//加锁,线程安全
            if (sPool != null) {
                Message m = sPool;//获得表头
                sPool = m.next; //更新表头
                m.next = null; //将返回的Message的next重置
                m.flags = 0; // clear in-use flag
                sPoolSize--; //更新缓存的Message数量
                return m;
            }
        }
        return new Message(); //不然新建一个
    }
}

3.缓存消息

  • 在Looper里面执行消息;
  • 执行完消息后,将Message缓存;
public final class Looper {
    public static void loop() {
        for (;;) {
            Message msg = queue.next();
            if (msg == null) {
                return;
            }
            msg.target.dispatchMessage(msg); //执行Message
            msg.recycleUnchecked(); //执行消息回收          
        }
    }
}
  • 执行消息回收;
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) {//只能缓存50个消息
            next = sPool; //每次执行完消息后,放这条消息放到头部
            sPool = this;//更换表头
            sPoolSize++;
        }
    }
}

你可能感兴趣的:(Android,android,Handler)