Message对象三种创建方法:
1.Message message = new message();
2.Message message = Message.obtain();
3.Message message = handler.obtainMessage(); 内部调用 Message.obtain();
Message.obtain();源码
由源码可知:Message内部有一个 消息池,
obtain是优先从消息池中取:
private static Message sPool;
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();
}
我们再来看看,Message是怎么放入消息池的:
消息回收的时候, 先将Message参数初始化,然后放入sPool
取出和放入代码块用的是相同的锁,所以是同步的
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++;
}
}
}