123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- package holeg.utility.pooling;
- import java.util.ArrayList;
- import java.util.stream.Stream;
- public abstract class Pool<T> {
- int borrowedCount = 0;
- private int poolCapacity = 1000;
- private final ArrayList<T> poolList = new ArrayList<>(poolCapacity);
- private final ArrayList<T> borrowedList = new ArrayList<>(poolCapacity);
- public Pool() {
- poppulatePool(poolCapacity);
- }
- public abstract T create();
- public T get() {
- checkCapacity(borrowedCount);
- T poolObject = poolList.get(borrowedCount);
- borrowedCount++;
- borrowedList.add(poolObject);
- return poolObject;
- }
- public void clear() {
- borrowedList.clear();
- borrowedCount = 0;
- }
- private void poppulatePool(int amount) {
- for (int i = 0; i < amount; i++) {
- poolList.add(create());
- }
- }
- private void checkCapacity(int requestedCapacity) {
- if (poolCapacity <= requestedCapacity) {
- int newSize = 2 * requestedCapacity;
- poppulatePool(newSize - poolCapacity);
- poolCapacity = 2 * requestedCapacity;
- }
- }
- public int getBorrowedCount() {
- return borrowedCount;
- }
- public Stream<T> getBorrowedStream() {
- return borrowedList.stream();
- }
- }
|