When it comes to object pooling, the key is to maintain your own list of available objects. This method works particularly well when all the objects are of the same type. For example, if you have a class called Thing, you could create a ThingPool.
import java.util.ArrayDeque;
import java.util.Deque;
public class ThingPool {
public static class Thing {
}
// Initialize a stack with a large number of objects
Deque<Thing> stack = new ArrayDeque<Thing>(1000);
/**
* Retrieves a new instance. If one is available in the stack, use that,
* otherwise create a new one.
* @return
*/
public Thing getThing() {
if(stack.isEmpty())
return new Thing();
return stack.pop();
}
/**
* Rather than deleting an object, simply store it for future use
* @param thing
*/
public void deleteThing(Thing thing) {
stack.push(thing);
}
/**
* It may be necessary to clear the pool at some point
* especially if there is a large number of objects stored
*/
public void clear() {
stack.clear();
}
}
I utilized this approach in my C programming days when dealing with numerous matrices of varying sizes and experiencing heap fragmentation issues.
Although I haven't applied it in Java, as Java benefits from superior memory management compared to C.