12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- package utility;
- import java.util.ArrayList;
- import java.util.stream.Stream;
- public abstract class Pool<T> {
- int borrowedCount = 0;
- private int poolCapacity = 1000;
- private ArrayList<T> poolList = new ArrayList<T>(poolCapacity);
- private ArrayList<T> borrowedList = new ArrayList<T>(poolCapacity);
-
-
- public abstract T create();
-
- public Pool(){
- poppulatePool(poolCapacity);
- }
-
- 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();
- }
-
- }
|