Class CloseableThreadLocal<T extends java.lang.AutoCloseable>

  • Type Parameters:
    T - The AutoCloseable type whose objects will be held by an object of this class.
    All Implemented Interfaces:

    public class CloseableThreadLocal<T extends java.lang.AutoCloseable>
    extends java.lang.Object
    implements java.lang.AutoCloseable
    A wrapper of ThreadLocal for AutoCloseable objects. Java's ThreadLocal only dereferences the thread-local objects when the Thread exits which triggers their garbage collection. It does not close the AutoCloseable thread-local objects.
    • Constructor Summary

      Constructor Description
      CloseableThreadLocal​(java.util.function.Supplier<T> initialValue)
      Creates a closeable thread local.
    • Method Summary

      All Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      void close()
      Clean up the resources held by this object.
      T get()
      Returns the value in the current thread's copy of this thread-local variable.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Constructor Detail

      • CloseableThreadLocal

        public CloseableThreadLocal​(java.util.function.Supplier<T> initialValue)
        Creates a closeable thread local. The initial value of the variable is determined by invoking the get method on the Supplier.
        initialValue - the supplier to be used to determine the initial value for each Thread
    • Method Detail

      • get

        public T get()
        Returns the value in the current thread's copy of this thread-local variable. If the variable has no value for the current thread, it is first initialized to the value returned by an invocation of the initialValue method.
        the current thread's value of this thread-local
      • close

        public void close()
        Clean up the resources held by this object. It triggers close on each thread's value. It is the responsibility of the caller to ensure that all threads have finished processing the thread-local objects.
        Specified by:
        close in interface java.lang.AutoCloseable