
org.cryptomator.cryptolib.common.ObjectPool Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of cryptolib Show documentation
Show all versions of cryptolib Show documentation
This library contains all cryptographic functions that are used by Cryptomator.
The newest version!
package org.cryptomator.cryptolib.common;
import java.lang.ref.WeakReference;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.function.Supplier;
/**
* A simple object pool for resources that are expensive to create but are needed frequently.
*
* Example Usage:
*
{@code
* Supplier fooFactory = () -> new Foo();
* ObjectPool fooPool = new ObjectPool(fooFactory);
* try (ObjectPool.Lease lease = fooPool.get()) { // attempts to get a pooled Foo or invokes factory
* lease.get().foo(); // exclusively use Foo instance
* } // releases instance back to the pool when done
* }
*
* @param Type of the pooled objects
*/
public class ObjectPool {
private final Queue> returnedInstances;
private final Supplier factory;
public ObjectPool(Supplier factory) {
this.returnedInstances = new ConcurrentLinkedQueue<>();
this.factory = factory;
}
public Lease get() {
WeakReference ref;
while ((ref = returnedInstances.poll()) != null) {
T cached = ref.get();
if (cached != null) {
return new Lease<>(this, cached);
}
}
return new Lease<>(this, factory.get());
}
/**
* A holder for resource leased from an {@link ObjectPool}.
* This is basically an {@link AutoCloseable autocloseable} {@link Supplier} that is intended to be used
* via try-with-resource blocks.
*
* @param Type of the leased instance
*/
public static class Lease implements AutoCloseable, Supplier {
private final ObjectPool pool;
private T obj;
private Lease(ObjectPool pool, T obj) {
this.pool = pool;
this.obj = obj;
}
public T get() {
return obj;
}
@Override
public void close() {
pool.returnedInstances.add(new WeakReference<>(obj));
obj = null;
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy