?我們使用消息時不要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();
}
}
使用一個消息后,消息池子相對應(yīng)會-1.
public static void loop() {
final Looper me = myLooper();
......
for (;;) {
Message msg = queue.next(); // might block
......
msg.target.dispatchMessage(msg);
msg.recycleUnchecked();
}
}
在調(diào)用完分發(fā)后狭莱,會執(zhí)行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艇抠。
總結(jié):有一些變量可以反復(fù)使用幕庐,這個時候為了減少不必要的gc(),考慮使用享元模式。