Skip to content

Instantly share code, notes, and snippets.

@douo
Last active March 8, 2017 02:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save douo/ad91b597a61f6825ca35 to your computer and use it in GitHub Desktop.
Save douo/ad91b597a61f6825ca35 to your computer and use it in GitHub Desktop.
一个实现 Recycle 机制的例子
/**
* Created by Tiou on 2014/7/15.
* 一个实现 Recycle 机制的对象
*/
public class Data {
/**
* 对象池,就是上文所提到的对象仓库,用于暂时存放不用的对象。
* 用链表来实现对象池结构,直观,高效,易用。
* sPool 便是指向链表头部的引用
*/
private static Data sPool;
/**
* 同步锁
*/
private static final Object sPoolSync = new Object();
/**
* 当前池中的对象数量
*/
private static int sPoolSize = 0;
/**
* 对象池的最大容量
*/
private static final int MAX_POOL_SIZE = 50;
/**
* 指向链表中的下一个元素,当 next 为 null 时表示已到达链表末端
*/
private Data next;
/**
* 隐藏构造函数,避免对象被 new 关键字创建
*/
private Data(){}
/**
* 从池里获取一个新对象,没有的话则返回一个新的实例
* @return 可用的新对象
*/
public static Data obtain(){
synchronized (sPoolSync) {
if (sPool != null) { // 池中有可用的对象
// 对于对象池来说顺序并没有关系
// 这里取链表的第一个对象,主要是因为方便
Data data = sPool;
sPool = sPool.next;
data.next = null;
sPoolSize--;
return data;
}
}
return new Data();
}
/**
* 将当前对象回收,一旦对象被回收,便不能再使用,代码中也不应存有任何到该对象的引用
*/
public void recycle(){
clear(); //清理对象
synchronized (sPoolSync){
//当对象池满后,回收的对象将直接交给 GC 回收
if(sPoolSize < MAX_POOL_SIZE) {
// 把当前对象作为首元素按入链表中
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
/**
* 重置对象到刚初始化时的状态
*/
private void clear(){
}
}
@ranjiexu
Copy link

ranjiexu commented Mar 8, 2017

good

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment