Package net.imglib2.util
Class CloseableThreadLocal<T>
- java.lang.Object
-
- net.imglib2.util.CloseableThreadLocal<T>
-
- All Implemented Interfaces:
java.io.Closeable,java.lang.AutoCloseable
- Direct Known Subclasses:
CloseableThreadLocal.SuppliedCloseableThreadLocal
public class CloseableThreadLocal<T> extends java.lang.Object implements java.io.CloseableJava's builtin ThreadLocal has a serious flaw: it can take an arbitrarily long amount of time to dereference the things you had stored in it, even once the ThreadLocal instance itself is no longer referenced. This is because there is single, master map stored for each thread, which all ThreadLocals share, and that master map only periodically purges "stale" entries.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, whereasclose()takes care of all threads. You should not callclose()until all threads are done using the instance.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description (package private) static classCloseableThreadLocal.SuppliedCloseableThreadLocal<T>
-
Field Summary
Fields Modifier and Type Field Description private java.util.concurrent.atomic.AtomicIntegercountUntilPurgeprivate java.util.Map<java.lang.Thread,T>hardRefsprivate static intPURGE_MULTIPLIERprivate java.lang.ThreadLocal<java.lang.ref.WeakReference<T>>t
-
Constructor Summary
Constructors Constructor Description CloseableThreadLocal()
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description voidclose()Tget()protected TinitialValue()private voidmaybePurge()private voidpurge()voidset(T object)static <S> CloseableThreadLocal<S>withInitial(java.util.function.Supplier<? extends S> supplier)Creates a thread local variable.
-
-
-
Method Detail
-
withInitial
public static <S> CloseableThreadLocal<S> withInitial(java.util.function.Supplier<? extends S> supplier)
Creates a thread local variable. The initial value of the variable is determined by invoking thegetmethod on theSupplier.
-
initialValue
protected T initialValue()
-
get
public T get()
-
set
public void set(T object)
-
maybePurge
private void maybePurge()
-
purge
private void purge()
-
close
public void close()
- Specified by:
closein interfacejava.lang.AutoCloseable- Specified by:
closein interfacejava.io.Closeable
-
-