Pool.java 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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 Pool() {
  10. poppulatePool(poolCapacity);
  11. }
  12. public abstract T create();
  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. }