前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Pool:小对象缓存or复用

Pool:小对象缓存or复用

作者头像
用户1172465
发布2018-01-08 14:34:38
5600
发布2018-01-08 14:34:38
举报
文章被收录于专栏:everhadeverhad

对象复用

使用链表作为pool来保存要复用的对象。

  • pool字段
  • obtain
  • recycle

案例1

android.os.Message

代码语言:javascript
复制
private static Message sPool;
 Message msg = mHandler.obtainMessage(MSG_PROCESS_INPUT_EVENTS);

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

案例2

android.view.ViewRootImpl

代码语言:javascript
复制
private QueuedInputEvent mQueuedInputEventPool;

QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags);


    private QueuedInputEvent obtainQueuedInputEvent(InputEvent event,
            InputEventReceiver receiver, int flags) {
        QueuedInputEvent q = mQueuedInputEventPool;
        if (q != null) {
            mQueuedInputEventPoolSize -= 1;
            mQueuedInputEventPool = q.mNext;
            q.mNext = null;
        } else {
            q = new QueuedInputEvent();
        }

        q.mEvent = event;
        q.mReceiver = receiver;
        q.mFlags = flags;
        return q;
    }

案例3

android.view.MotionEvent

代码语言:javascript
复制
private static MotionEvent gRecyclerTop;

  static private MotionEvent obtain() {
        final MotionEvent ev;
        synchronized (gRecyclerLock) {
            ev = gRecyclerTop;
            if (ev == null) {
                return new MotionEvent();
            }
            gRecyclerTop = ev.mNext;
            gRecyclerUsed -= 1;
        }
        ev.mNext = null;
        ev.prepareForReuse();
        return ev;
    }

    /**
     * Recycle the MotionEvent, to be re-used by a later caller.  After calling
     * this function you must not ever touch the event again.
     */
    @Override
    public final void recycle() {
        super.recycle();

        synchronized (gRecyclerLock) {
            if (gRecyclerUsed < MAX_RECYCLED) {
                gRecyclerUsed++;
                mNext = gRecyclerTop;
                gRecyclerTop = this;
            }
        }
    }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-01-22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 对象复用
  • 案例1
  • 案例2
  • 案例3
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档