zoukankan      html  css  js  c++  java
  • Pool:小对象缓存or复用

    对象复用

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

    • pool字段
    • obtain
    • recycle

    案例1

    android.os.Message

    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

    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

    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;
                }
            }
        }
    
  • 相关阅读:
    Dobbo
    Redis
    Sql语句模糊查询字符串的两种写法
    Python——labelImg安装
    Python——numpy中的 sum 函数
    Python——pymysql 操作数据库
    Axure RP9 授权码和密钥
    更改 pip install 默认安装依赖的路径(转载)
    pip 升级或者安装拓展包时遇见的问题
    在Windows命令行中编译运行C/C++程序(转载)
  • 原文地址:https://www.cnblogs.com/everhad/p/6341551.html
Copyright © 2011-2022 走看看