Android Message实现处理大致如下
涉及到的几个问题
- Message的数据结构:通过next成员,保持一种链表的链接关系
// sometimes we store linked lists of these things /*package*/ Message next;
- pool的处理
- 形式:就是一个静态的节点,由于next的链表结构,能够保持一种链接。其中sPool总是指向最上面的meesage pool中最上面的message对象。
private static Message sPool;
- 大小:
- 初始大小
private static int sPoolSize = 0;
- 限制大小
private static final int MAX_POOL_SIZE = 10;
- 初始大小
- 形式:就是一个静态的节点,由于next的链表结构,能够保持一种链接。其中sPool总是指向最上面的meesage pool中最上面的message对象。
- 增长
public void recycle() { clearForRecycle(); synchronized (sPoolSync) { if (sPoolSize < MAX_POOL_SIZE) {//判断大小是否满足最大值 next = sPool; sPool = this; sPoolSize++;//设置增长 } } }
- 减少
public static Message obtain() { synchronized (sPoolSync) { if (sPool != null) { Message m = sPool; sPool = m.next; m.next = null; sPoolSize--;//减少 return m; } } return new Message(); }
- 增长
- 节点增删
- 向pool中添加节点
public void recycle() { clearForRecycle(); synchronized (sPoolSync) { if (sPoolSize < MAX_POOL_SIZE) {//判断当前pool的大小,当已经满足pool的上限的时候,不再添加 next = sPool;//把当前节点的next指向pool中最上面的节点,建立链表关系 sPool = this;//把sPool指针上移,指向新添加的节点 sPoolSize++; } } }
- 从pool中获取节点
public static Message obtain() { synchronized (sPoolSync) { if (sPool != null) {//判断pool是不是空的,如果非空,从pool里取出最上面的节点 Message m = sPool;//获取最上面message的引用 sPool = m.next;//sPool节点下移,相当于将上面的节点弹出。 m.next = null; sPoolSize--;//大小减一 return m; } } return new Message();//如果pool是空的,直接创建一个新的message去使用 }
- 向pool中添加节点
- 线程安全
- 同步对象
private static final Object sPoolSync = new Object();
- 增删加锁
public static Message obtain() { synchronized (sPoolSync) { if (sPool != null) {//加锁 ...//从pool中弹出message } } .... }
public void recycle() { .... synchronized (sPoolSync) {//加锁 if (sPoolSize < MAX_POOL_SIZE) { ...//向pool中添加message } } }
- 同步对象