Class ObjectPool<T extends Reusable>

java.lang.Object
Creational.ObjectPool.ObjectPool<T>
Type Parameters:
T - The type of objects managed by the pool, which must implement the Reusable interface.

public class ObjectPool<T extends Reusable> extends Object
Generic Object Pool for managing reusable objects. The ObjectPool class provides a way to manage and reuse a pool of objects, reducing the overhead of repeatedly creating and destroying objects. Objects implementing the Reusable interface can be added to the pool, borrowed, and returned for reuse.
  • Constructor Details

    • ObjectPool

      public ObjectPool()
      Constructs an empty ObjectPool.
  • Method Details

    • addObject

      public void addObject(T obj)
      Adds a reusable object to the pool.
      Parameters:
      obj - The reusable object to be added to the pool.
      Throws:
      IllegalArgumentException - if the object is null.
    • borrowObject

      public T borrowObject()
      Borrows a reusable object from the pool.
      Returns:
      A reusable object from the pool.
      Throws:
      IllegalStateException - if the pool is empty.
    • returnObject

      public void returnObject(T obj)
      Returns a reusable object to the pool. The returned object is reset to its initial state before being added back to the pool.
      Parameters:
      obj - The reusable object to return to the pool.
      Throws:
      IllegalArgumentException - if the object is null.
    • getSize

      public int getSize()
      Gets the current size of the pool.
      Returns:
      The number of reusable objects currently in the pool.