Search in sources :

Example 1 with Action

use of org.spf4j.recyclable.ObjectBorower.Action in project spf4j by zolyfarkas.

the class SimpleSmartObjectPool method tryDispose.

@Override
public boolean tryDispose(final long timeoutMillis) throws ObjectDisposeException, InterruptedException {
    factory.dispose(sample);
    long deadlineNanos = TimeSource.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeoutMillis);
    lock.lock();
    try {
        maxSize = 0;
        List<Pair<ObjectBorower<T>, T>> returnedObjects = new ArrayList<>();
        for (Entry<ObjectBorower<T>, Collection<T>> b : borrowedObjects.asMap().entrySet()) {
            ObjectBorower<T> borrower = b.getKey();
            final int nrObjects = b.getValue().size();
            for (int i = 0; i < nrObjects; i++) {
                Either<Action, T> object = borrower.tryRequestReturnObject();
                if (object.isRight()) {
                    returnedObjects.add(Pair.of(borrower, object.getRight()));
                }
            }
        }
        for (Pair<ObjectBorower<T>, T> objectAndBorrower : returnedObjects) {
            T object = objectAndBorrower.getSecond();
            if (!borrowedObjects.remove(objectAndBorrower.getFirst(), object)) {
                throw new IllegalStateException("Returned Object hasn't been borrowed " + object);
            }
            availableObjects.add(object);
        }
        ObjectDisposeException exception = disposeReturnedObjects(null);
        while (!borrowedObjects.isEmpty()) {
            long waitTimeNanos = deadlineNanos - TimeSource.nanoTime();
            if (waitTimeNanos <= 0) {
                return false;
            }
            if (!available.await(waitTimeNanos, TimeUnit.NANOSECONDS)) {
                return false;
            }
            exception = disposeReturnedObjects(exception);
        }
        if (exception != null) {
            throw exception;
        }
        return true;
    } catch (InterruptedException | RuntimeException e) {
        throw e;
    } finally {
        lock.unlock();
    }
}
Also used : ObjectBorower(org.spf4j.recyclable.ObjectBorower) Action(org.spf4j.recyclable.ObjectBorower.Action) ArrayList(java.util.ArrayList) ObjectDisposeException(org.spf4j.recyclable.ObjectDisposeException) Collection(java.util.Collection) Pair(org.spf4j.base.Pair)

Aggregations

ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 Pair (org.spf4j.base.Pair)1 ObjectBorower (org.spf4j.recyclable.ObjectBorower)1 Action (org.spf4j.recyclable.ObjectBorower.Action)1 ObjectDisposeException (org.spf4j.recyclable.ObjectDisposeException)1