a few points
- Object creation
- Object reuse
- Object recycling
- Object memory release
Solution 1: Bean object with object pool
package chenggong.test;
import java.util.Objects;
public class ObjectPool {
private static final String TAG = "ObjectPool";
private static final Object POOL_LOCK = new Object();
private static final int MAX_POOL_SIZE = 20;
private static ObjectPool sPool;
private static int sPoolSize;
private String name;
private int number;
private ObjectPool next;
public ObjectPool() {
}
public ObjectPool(String name, int number) {
this.name = name;
this.number = number;
}
public static ObjectPool obtain() {
obtain(null, 0);
}
public static ObjectPool obtain(String name, int number) {
synchronized (POOL_LOCK) {
if (sPool != null) {
ObjectPool object = sPool;
sPool = object.next;
object.next = null;
sPoolSize--;
object.name = name;
object.number = number;
return object;
}
}
return new ObjectPool(name, number);
}
public void recycle() {
name = null;
number = 0;
synchronized (POOL_LOCK) {
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
public static void release() {
synchronized (POOL_LOCK) {
sPool = null;
sPoolSize = 0;
}
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ObjectPool))
return false;
ObjectPool that = (ObjectPool) o;
return number == that.number && Objects.equals(name, that.name);
}
@Override
public int hashCode() {
return Objects.hash(name, number);
}
@Override
public String toString() {
return "ObjectPool{" + "name=" + name + ", number=" + number + '}';
}
}
Solution 2 object pool template
package chenggong.test;
import java.util.LinkedList;
import java.util.Objects;
import android.util.Log;
public class ObjectPool<T> {
private static final String TAG = "ObjectPool";
private static final int MAX_POOL_SIZE = 20;
private final Object mPoolLock = new Object();
private LinkedList<T> mPool;
private Factory<T> mFactory;
public ObjectPool(Factory<T> factory) {
mFactory = factory;
mPool = new LinkedList<>();
}
public T obtain() {
synchronized (mPoolLock) {
if (!mPool.isEmpty()) {
return mPool.removeFirst();
}
}
return mFactory.create();
}
public void recycle(T t) {
mFactory.recycle(t);
synchronized (mPoolLock) {
if (mPool.size() < MAX_POOL_SIZE) {
mPool.add(t);
}
}
}
public void release() {
synchronized (mPoolLock) {
Log.i(TAG, "mPool size is " + mPool);
mPool.clear();
}
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ObjectPool))
return false;
ObjectPool<?> that = (ObjectPool<?>) o;
return Objects.equals(mPool, that.mPool) && Objects.equals(mFactory, that.mFactory);
}
@Override
public int hashCode() {
return Objects.hash(mPool, mFactory);
}
@Override
public String toString() {
return "ObjectPool{" + "mPool=" + mPool + ", mFactory=" + mFactory + '}';
}
}
package chenggong.test;
public interface Factory<T> {
T create();
void recycle(T t);
}