/** * Get a element from the pool. If there is an available element in * the pool, it will be returned. Otherwise, if the number of active * elements does not exceed the limit, a new element is created with * create() and returned. Otherwise, blocks until an element is either * released and returned to the pool, or an element is discarded, * allowing for the creation of a new element. * * @return an element */ public T obtain() throws E, InterruptedException { semaphore.acquire(); return getOrCreate(); }
/** * Get a element from the pool. If there is an available element in * the pool, it will be returned. Otherwise, if the number of active * elements does ot exceed the limit, a new element is created with * create() and returned. Otherwise, blocks until an element is either * released and returned to the pool, an element is discarded, * allowing for the creation of a new element, or a timeout occurs. * * @param timeout the timeout for trying to obtain an element * @param unit the timeout unit for trying to obtain an element * @return an element * @throws TimeoutException if a client is not able to be obtained within the given timeout */ public T obtain(long timeout, TimeUnit unit) throws E, TimeoutException, InterruptedException { if (!semaphore.tryAcquire(1, timeout, unit)) { throw new TimeoutException(String.format("Failed to obtain client within %d %s.", timeout, unit)); } return getOrCreate(); }