前言
在使用Message时,很感兴趣如何实现复用机制的,也好自己可以实现一个类似的东西,于是便花几分钟来理一下思路,权当备忘,大家也可以参考参考。
数据类型
/*package*/
Message next;//指向下一个引用
private static final Object sPoolSync = new Object(); //对象锁
private static Message sPool;//共享变量池
回收逻辑
/**
* 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();
}
/**
* 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++;
}
}
}
复用逻辑
/**
* 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();
}
备忘
sPool是一个指向Message类型数据的引用(现阶段可认为是一个共享池),next也是一个Message对象引用,可以认为是伪造的链表的一端。
在recycle时,会将该Message对象放到共享池中;
在obtain时,会从共享池中获取Message对象;
当第一个Message对象被recycle时,会将自身赋值给sPool,并将next指向null。此时,第二次回收:next 获取第一个被recycle回收的对象的引用,自己成为一个(sPool)变量池指代。以此类推,一一入栈。
在obtain第一个Message对象时,因为sPool = null,所以第一个对象是new 出来的;在obtain第二次执行的时候,sPool != null ,此时获取到sPool,将sPool的下一个对象作为sPool,并将m.next 置空,从栈中弹出。
思路总结
伪造堆栈的思路确实挺不错的。我们在回收时,总会把用过的Message对象放到最顶端,使用的时候也是从最顶端获取。维持一个固定的堆栈的大小。