public V getResource(K iKey, final long iMaxWaitMillis, Object... iAdditionalArgs) throws OLockException {
// First, get permission to take or create a resource
try {
if (!sem.tryAcquire(iMaxWaitMillis, TimeUnit.MILLISECONDS))
throw new OLockException("Can't acquire lock on requested resource: " + iKey);
} catch (InterruptedException e) {
throw new OLockException("Can't acquire lock on requested resource: " + iKey, e);
}
// Then, actually take one if available...
V res = resources.poll();
if (res != null) {
listener.reuseResource(iKey, iAdditionalArgs, res);
return res;
}
// ...or create one if none available
try {
res = listener.createNewResource(iKey, iAdditionalArgs);
return res;
} catch (Exception e) {
// Don't hog the permit if we failed to create a resource!
sem.release();
throw new OLockException("Error on creation of the new resource in the pool", e);
}
}