为什么Message创建对象使用Message.Obtain而不是使用new 这个关键字
附上关键源码:
/**
* Return a new Message instance from the global pool. Allows us to
* avoid allocating new objects in many cases.
* 返回一个消息的实例从线程池当中,避免生成一个新的实例;
*/
private static final Object sPoolSync = new Object();
private static Message sPool;
private static int sPoolSize = 0;
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
sPoolSize--;
return m;
}
}
return new Message();
}
总结:只有当消息的实例为空的时候才会去生成一个对象,如果实例不为空可以直接从消息池中获得
实例,防止对象重复创建。