de.team33.patterns.pooling.ariel.Mutual Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of pooling-ariel Show documentation
Show all versions of pooling-ariel Show documentation
Provides a simple pooling of "expensive", reusable but thread-sensitive instances.
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 super S, X> xConsumer) throws E, X {
apply(subject -> {
xConsumer.accept(subject);
return VOID;
});
}
final R apply(final XFunction super S, R, X> 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();
}
}