Pool.java 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package holeg.utility.pooling;
  2. import java.util.ArrayList;
  3. import java.util.stream.Stream;
  4. public abstract class Pool<T> {
  5. int borrowedCount = 0;
  6. private int poolCapacity = 1000;
  7. private final ArrayList<T> poolList = new ArrayList<>(poolCapacity);
  8. private final ArrayList<T> borrowedList = new ArrayList<>(poolCapacity);
  9. public abstract T create();
  10. public Pool(){
  11. poppulatePool(poolCapacity);
  12. }
  13. public T get(){
  14. checkCapacity(borrowedCount);
  15. T poolObject = poolList.get(borrowedCount);
  16. borrowedCount++;
  17. borrowedList.add(poolObject);
  18. return poolObject;
  19. }
  20. public void clear() {
  21. borrowedList.clear();
  22. borrowedCount = 0;
  23. }
  24. private void poppulatePool(int amount) {
  25. for(int i= 0; i < amount; i++) {
  26. poolList.add(create());
  27. }
  28. }
  29. private void checkCapacity(int requestedCapacity) {
  30. if(poolCapacity <= requestedCapacity) {
  31. int newSize = 2 * requestedCapacity;
  32. poppulatePool(newSize - poolCapacity);
  33. poolCapacity = 2*requestedCapacity;
  34. }
  35. }
  36. public int getBorrowedCount() {
  37. return borrowedCount;
  38. }
  39. public Stream<T> getBorrowedStream(){
  40. return borrowedList.stream();
  41. }
  42. }