介绍
Message其实没有什么好说的,就是一个普通的数据类,但是它的循环使用的机制挺有趣的:Message通过一个静态Message变量sPool,和本身有的Message属性,构成了一个链表,通过obtain和recycleUnchecked方法分别从这个链表中读取和添加节点,以此达到循环使用Message的目的,以下是这两个方法的源码。
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();
}
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++;
}
}
}