使用鏈表做爲pool來保存要複用的對象。java
android.os.Messageandroid
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(); }
android.view.ViewRootImplide
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; }
android.view.MotionEventthis
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; } } }