带生命周期的对象池java实现
时间: 2023-07-25 07:37:43 浏览: 93
以下是Java实现带生命周期的对象池的示例代码:
```
import java.util.concurrent.ConcurrentLinkedQueue;
public abstract class ObjectPool<T> {
private ConcurrentLinkedQueue<T> pool;
public ObjectPool(final int size) {
pool = new ConcurrentLinkedQueue<T>();
for (int i = 0; i < size; i++) {
pool.add(createObject());
}
}
protected abstract T createObject();
public T borrowObject() {
T object;
if ((object = pool.poll()) == null) {
object = createObject();
}
onBorrow(object);
return object;
}
public void returnObject(T object) {
onReturn(object);
pool.offer(object);
}
protected void onBorrow(T object) {
// Optional: Implement this method to perform additional operations when an object is borrowed from the pool.
}
protected void onReturn(T object) {
// Optional: Implement this method to perform additional operations when an object is returned to the pool.
}
}
```
在上述代码中,我们定义了一个泛型类ObjectPool,其中保存了对象池的所有对象。在对象池的构造函数中,我们首先添加了一定数量的对象,以满足最大并发需求。borrowObject()方法用于从对象池中获取对象,如果对象池为空,则会创建一个新对象。returnObject()方法用于将对象放回对象池中。onBorrow()和onReturn()方法用于在借用和归还对象时执行附加操作。
使用示例:
```
public class MyObjectPool extends ObjectPool<MyObject> {
public MyObjectPool(int size) {
super(size);
}
@Override
protected MyObject createObject() {
return new MyObject();
}
}
public class MyObject {
public void onSpawn() {
// Implement this method to perform initialization operations when an object is borrowed from the pool.
}
public void onDespawn() {
// Implement this method to perform cleanup operations when an object is returned to the pool.
}
}
// 使用示例
MyObjectPool pool = new MyObjectPool(10);
MyObject obj = pool.borrowObject();
obj.onSpawn();
// Use the object
obj.onDespawn();
pool.returnObject(obj);
```
在上述代码中,我们首先定义了一个对象池MyObjectPool,它是ObjectPool的子类,并且根据需要实现了createObject()方法。在MyObject类中,我们实现了onSpawn()和onDespawn()方法,用于在对象被借用和归还时执行初始化和清理操作。在使用示例中,我们首先从对象池中借用了一个对象,然后在使用前调用了onSpawn()方法,在使用完后调用了onDespawn()方法,并将对象归还到对象池中。
阅读全文