When Handler is used, when we use the Message object, google does not recommend us to construct a Message object through new Message (), because the Message will be frequently used, constantly new, this results in memory fragmentation and low efficiency. Google recommends that we construct it using the obtain () method. Why? How does obtain () construct messages internally to avoid wasting time due to frequent new requests?
First, let's look at the obtain () function:
(sPool != Message m = sPool = m.next = sPoolSize-- }
Other overloaded obtain () functions call obtain (), so you only need to understand this one.
First Judge sPool! = Null. Here sPool is a static internal object of Message:
Private static Message sPool;
If we call sPool for the first time, it must be null, then the function will directly execute return new Message. After sPool is executed, it is still null. Is the sPool initialized? We can see that it is initialized in recycle.
(sPoolSize < next = sPool = sPoolSize++ }
This function is called in many places, but mainly in logoff. in loop (), collection is implemented here. At the beginning, sPoolSize is smaller than MAX_POOL_SIZE (this value is 10), so every call to recycle (), sPool, And next will be assigned a value, sPoolSize ++ until sPoolSize = MAX_POOL_SIZE. In the sPoolSize ++ process, sPoll points to the caller object and retains the reference of this object. next refers to the reference of the previous object. Note that next is an internal attribute Member of the Message, it is not static, so a one-way linked list is formed. Each node is the Message object that calls the recycle () method. The maximum length of the linked list is MAX_POOL_SIZE.
Let's look back at obtain (). When sPool! = Null, m = sPool, which is used as the return value, and then assigned a value to sPool: sPool = m. next, then m. next = null, sPoolSize --. This operation is actually the operation to delete the last node of the linked list and return it. It can be seen that the original new Message object is returned here and reused.
The Message queue in Handler is actually a Message object. That is to say, Message writing is not maintained by MessageQueue, but implemented by the Message itself.