Android开发Message源码分析【享元模式|对象池】

来源:互联网 发布:量子工作室 知乎 编辑:程序博客网 时间:2024/06/05 12:46

享元模式介绍

享元模式是对象池的一种实现,尽可能减少内存的使用,使用缓存来共享可用的对象,避免创建过多的对象。Android中Message使用的设计模式就是享元模式,获取Message通过obtain方法从对象池获取,Message使用结束通过recycle将Message归还给对象池,达到循环利用对象,避免重复创建的目的

Message源码分析

Message中有关于对象池的属性如下:

Message next;
private static final Object sPoolSync = new Object();
private static Message sPool;
private static int sPoolSize = 0;
private static final int MAX_POOL_SIZE = 50

采用链表的形式达到对象池的功能,next为指向对象池下一个对象的指针,sPool始终指向链表队首,sPoolSize表示当前链表数据量,MAX_POOL_SIZE表示对象池容量,sPoolSync专门用来给对象池上锁,达到互斥访问的目的。
注意命名规则,static变量以小写字母s开头,static final 为常量,全部大写

使用obtain从对象池获取Message对象

   /**     * Return a new Message instance from the global pool. Allows us to     * avoid allocating new objects in many cases.     */    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();    }

对象池属于临界区,访问需要加锁,这里并没有使用synchronized修饰obtain方法,是为了减小锁的粒度。
可见obtain方法首先判断对象池是否为空,空的话直接通过构造方法创建一个新的Message对象返回。不空的话从链表头部取出一个Message对象,链表头指针指向下一个对象,将该Message对象next指针域置空,标志位置空,对象池对象数量大小减一,返回这个Message对象

使用recycle方法回收Message对象

    /**     * Return a Message instance to the global pool.     * <p>     * You MUST NOT touch the Message after calling this function because it has     * effectively been freed.  It is an error to recycle a message that is currently     * enqueued or that is in the process of being delivered to a Handler.     * </p>     */    public void recycle() {        if (isInUse()) {            if (gCheckRecycle) {                throw new IllegalStateException("This message cannot be recycled because it "                        + "is still in use.");            }            return;        }        recycleUnchecked();    }

recycle方法回收的对象必须是可回收的,即已经不再使用的,否则的话抛出异常。

 /**     * 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++;            }        }    }

回收方法是把Message对象的所有标志位清空,数据清空,然后将此回收的Message对象加入到链表的头部,这样一个废弃的Message对象就被回收了。

0 0
原创粉丝点击