?我们使用消息时不要new出Message,要使用Message提供给我们的obtain方法。
Message msg = Message.obtain();
public final class Message implements Parcelable {
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();
}
}
使用一个消息后,消息池子相对应会-1.
public static void loop() {
final Looper me = myLooper();
......
for (;;) {
Message msg = queue.next(); // might block
......
msg.target.dispatchMessage(msg);
msg.recycleUnchecked();
}
}
在调用完分发后,会执行recycleUnchecked 回收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 = UID_NONE;
workSourceUid = UID_NONE;
when = 0;
target = null;
callback = null;
data = null;
synchronized (sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
在recycleUnchecked中,会做一个置空的操作,然后sPool 会+1。
总结:有一些变量可以反复使用,这个时候为了减少不必要的gc(),考虑使用享元模式。