public class ResourcePool<R extends AutoCloseable> extends Object implements AutoCloseable
Resources are lazily created up till a fixed maximum. If more than max resources are requested the associated 'requests' are queued up in the resourceRequests field. As soon as a resource is returned it will be used to satisfy the first pending request, otherwise it is stored in the parkedResources queue.
If the resourceSupplier throws a RuntimeException the Future associated with the failed attempt to create the resource will contain the relevant exception. Any subsequent requests the pool will get will attempt to create a new resource.
If the ResourcePool.ResourceUsageErrorPolicy.RECYCLE
error usage policy is specified then, in case
of errors when "using" a resource it is assumed to be defective, will be retired and a new
resource will be requested from the supplier. The Future associated with the failed attempt to
use the resource will contain the relevant exception.
Modifier and Type | Class and Description |
---|---|
static class |
ResourcePool.ResourceUsageErrorPolicy
Describes how to handle errors that take place during resource usage.
|
static interface |
ResourcePool.ThrowingFunction<T,R> |
Constructor and Description |
---|
ResourcePool(int maxResources,
ResourcePool.ResourceUsageErrorPolicy resourceUsageErrorPolicy,
java.util.function.Supplier<R> resourceSupplier) |
Modifier and Type | Method and Description |
---|---|
void |
callOnEachResource(java.util.function.Consumer<R> withResource) |
void |
close() |
com.google.common.util.concurrent.ListenableFuture<Unit> |
getShutdownFullyCompleteFuture() |
<T> com.google.common.util.concurrent.ListenableFuture<T> |
scheduleOperationWithResource(ResourcePool.ThrowingFunction<R,T> withResource,
com.google.common.util.concurrent.ListeningExecutorService executorService) |
public ResourcePool(int maxResources, ResourcePool.ResourceUsageErrorPolicy resourceUsageErrorPolicy, java.util.function.Supplier<R> resourceSupplier)
maxResources
- maximum number of resources to use concurrently.resourceSupplier
- function used to create a new resource. It should never block, it may
be called more than maxResources times if processing resources throws exceptions.public void callOnEachResource(java.util.function.Consumer<R> withResource)
public <T> com.google.common.util.concurrent.ListenableFuture<T> scheduleOperationWithResource(ResourcePool.ThrowingFunction<R,T> withResource, com.google.common.util.concurrent.ListeningExecutorService executorService)
executorService
- where to perform the resource processing. Should really be a "real"
executor (not a directExecutor).ListenableFuture
containing the result of the processing. The future will be
cancelled if the close()
method is called.@Nullable public com.google.common.util.concurrent.ListenableFuture<Unit> getShutdownFullyCompleteFuture()
public void close()
close
in interface AutoCloseable