T
- type of instances returned by this ThreadLocalHolder
.public class ThreadLocalHolder<T> extends Object
Supplier
given to the constructor.
A thread obtains the value by calling acquire()
and must release it after
use by calling release()
. If the value is not released, subsequent calls to
acquire()
will throw an IllegalStateException
.
Instances value may also implement the optional ThreadLocalHolder.Lifecycle
interface if they wish to be notified when they are recycled or disposed.
The holder keeps track of each requesting thread and takes care of disposing the
allocated value when it dies.
All allocated values are automatically disposed when close()
is called.
Note: This class is for internal use only and subject to backward incompatible change at any time.
Modifier and Type | Class and Description |
---|---|
protected class |
ThreadLocalHolder.HolderRef
A
WeakReference to a thread with the Holder assigned to it. |
static interface |
ThreadLocalHolder.Lifecycle
Optional interface that pooled instances may implement if they wish to be notified of
life cycle events.
|
Modifier and Type | Field and Description |
---|---|
protected Map<Long,ThreadLocalHolder.HolderRef> |
threadValues
Collection of values assigned to each thread
|
Constructor and Description |
---|
ThreadLocalHolder(Supplier<T> factory)
Create a new instance of the pool.
|
Modifier and Type | Method and Description |
---|---|
T |
acquire()
Get the value assigned to the current thread, creating a new one if none is assigned yet or the
previous has been disposed.
|
void |
close()
Close the holder and dispose all values.
|
protected T |
createInstance()
Create a new object instance (must be non-null).
|
protected void |
disposeInstance(T instance)
Dispose the object instance by calling its life cycle methods.
|
protected boolean |
recycleInstance(T instance)
Recycle the instance before returning it to the pool.
|
void |
release()
Release the value and recycle it if possible.
|
protected final Map<Long,ThreadLocalHolder.HolderRef> threadValues
public final T acquire()
release()
to ensure proper life cycle before it can be acquire()
again.IllegalStateException
- if the value is already in use and release()
was not yet invoked.public final void release()
IllegalStateException
- if the value was not previously acquire()
.public void close()
protected T createInstance()
protected void disposeInstance(T instance)
instance
- the instance to disposeprotected boolean recycleInstance(T instance)
instance
- the instance to recycletrue
if the instance can be recycled and returned to the pool, false
if not.Copyright © 2013–2022. All rights reserved.