public class CloseableThreadLocal<T> extends Object implements Closeable
While not technically a memory leak, because eventually the memory will be reclaimed, it can take a long time and you can easily hit OutOfMemoryError because from the GC's standpoint the stale entries are not reclaimable.
This class works around that, by only enrolling WeakReference values into the ThreadLocal, and
separately holding a hard reference to each stored value. When you call close(), these
hard references are cleared and then GC is freely able to reclaim space by objects stored in it.
We can not rely on ThreadLocal.remove() as it only removes the value for the caller
thread, whereas close() takes care of all threads. You should not call close()
until all threads are done using the instance.
| Constructor and Description |
|---|
CloseableThreadLocal() |
| Modifier and Type | Method and Description |
|---|---|
void |
close() |
T |
get() |
protected T |
initialValue() |
void |
set(T object) |
static <S> CloseableThreadLocal<S> |
withInitial(Supplier<? extends S> supplier)
Creates a thread local variable.
|
public static <S> CloseableThreadLocal<S> withInitial(Supplier<? extends S> supplier)
get method on the Supplier.protected T initialValue()
public T get()
public void set(T object)
public void close()
close in interface Closeableclose in interface AutoCloseableCopyright © 2009–2024 ImgLib2. All rights reserved.