/** @noinspection UnusedDeclaration*/ class LimitedPool { private int capacity; private final ObjectFactory factory; private Object[] storage; private int index = 0; public LimitedPool(final int capacity, ObjectFactory factory) { this.capacity = capacity; this.factory = factory; storage = new Object[capacity]; } interface ObjectFactory { T create(); void cleanup(T t); } public T alloc() { if (index >= capacity) return factory.create(); if (storage[index] == null) { storage[index] = factory.create(); } return storage; } }