public class RecyclableObject { /** * 对象池的大小 若是对象池满 则不会再将东西加入进去 */ private static final int MAX_POOL_SIZE = 50; /** * 表明是否该对象已经在对象池里 */ private static final int FLAG_IN_POOL = 1; /** * 同步锁 若是多个线程同时调用Obtain方法,对其进行同步 */ private static final Object sPoolSync = new Object(); /** * 对象池的起点 */ private static RecyclableObject sPool; /** * 对象池大小 */ private static int sPoolSize = 0; /** * 用于标志是否在对象池里 */ private int flags; /** * 当对象 在对象池里 链接下一个对象池中的对象 * object -> object -> object */ private RecyclableObject next; /** * 经过obtain获取到的对象 有可能会复用对象池的对象 减小内存压力 * @return 可循环用的对象 */ public static RecyclableObject obtain() { synchronized (sPoolSync) { if (sPool != null) { RecyclableObject m = sPool; sPool = m.next; m.next = null; m.flags = 0; // clear in-poll flag sPoolSize--; return m; } } return new RecyclableObject(); } /** * 当对象再也不须要时,清理完里面的数据,而后调用此方法,能将它释放到对象池里,注意 * 一旦recycle,外界尽可能不要有它的引用了 */ public void recycle() { if (isInPool()) { throw new IllegalStateException("This object cannot be recycled because it " + "is still in use."); } recycleUnchecked(); } private void recycleUnchecked() { // Mark the object as in use while it remains in the recycled object pool. // Clear out all other details. flags = FLAG_IN_POOL; synchronized (sPoolSync) { if (sPoolSize < MAX_POOL_SIZE) { next = sPool; sPool = this; sPoolSize++; } } } /** * 将已经recycle的对象设置为in use,表明已经在对象池里 防止对一个对象屡次recycle 而后出现循环链表 * @return */ private boolean isInPool() { return ((flags & FLAG_IN_POOL) == FLAG_IN_POOL); }}