public abstract class TemporaryObjectAllocator<T> extends Object
This technique is useful for temporary counter arrays in faceted search
FacetsAccumulator), which can be reused across searches instead
of being allocated afresh on every search.
A TemporaryObjectAllocator is thread-safe.
|Constructor and Description|
Construct an allocator for objects of a certain type, keeping around a pool of up to
|Modifier and Type||Method and Description|
Allocate a new object.
Subclasses must override this method to clear an existing object of the desired type, to prepare it for reuse.
Subclasses must override this method to actually create a new object of the desired type.
Return a no-longer-needed object back to the pool.
public TemporaryObjectAllocator(int maxObjects)
Note that the pool size only restricts the number of objects that hang around when not needed, but not the maximum number of objects that are allocated when actually is use: If a number of concurrent threads ask for an allocation, all of them will get an object, even if their number is greater than maxObjects. If an application wants to limit the number of concurrent threads making allocations, it needs to do so on its own - for example by blocking new threads until the existing ones have finished. If more than maxObjects are freed, only maxObjects of them will be kept in the pool - the rest will not and will eventually be garbage-collected by Java.
In particular, when maxObjects=0, this object behaves as a trivial allocator, always allocating a new array and never reusing an old one.
protected abstract T create()
protected abstract void clear(T object)
public final T allocate()
Don't forget to call
free(Object) when you're done with the object,
to return it to the pool. If you don't, memory is not leaked,
but the pool will remain empty and a new object will be allocated each
time (just like the maxArrays=0 case).
public final void free(T object)
In particular, when maxArrays=0, the given array is never saved and free does nothing.