All Downloads are FREE. Search and download functionalities are using the official Maven repository.

de.team33.patterns.pooling.ariel.Mutual Maven / Gradle / Ivy

Go to download

Provides a simple pooling of "expensive", reusable but thread-sensitive instances.

There is a newer version: 1.21.0
Show newest version
package de.team33.patterns.pooling.ariel;

import de.team33.patterns.exceptional.dione.XConsumer;
import de.team33.patterns.exceptional.dione.XFunction;
import de.team33.patterns.exceptional.dione.XSupplier;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

class Mutual {

    private static final Void VOID = null;

    private final Queue> stock = new ConcurrentLinkedQueue<>();
    private final XSupplier, E> newItem;

    Mutual(final XSupplier, E> newItem) {
        this.newItem = newItem;
    }

    final  void accept(final XConsumer xConsumer) throws E, X {
        apply(subject -> {
            xConsumer.accept(subject);
            return VOID;
        });
    }

    final  R apply(final XFunction function) throws E, X {
        final XSupplier stocked = stock.poll();
        final XSupplier item = (null == stocked) ? newItem.get() : stocked;
        try {
            return function.apply(item.get());
        } finally {
            stock.add(item);
        }
    }

    /**
     * Returns the number of currently unused subjects in stock.
     */
    public final int size() {
        return stock.size();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy