Class ThreadLocalStack<T>

  • Direct Known Subclasses:
    CurrentEventMetadata, CurrentInjectionPoint

    public class ThreadLocalStack<T>
    extends Object
    A stack that is kept in thread-local. Two operations were identified to be expensive in micro benchmarks:
    • ThreadLocal.set()
    • ThreadLocal.get() if the current value is null (because such get involves setting the initial value)
    Therefore this implementation tries to optimize that. First of all we make use of RequestScopedCache for cleaning up the thread local. If RequestScopedCache is active we do not remove the stack from thread local immediately when it becomes empty but defer this to the point when RequestScopedCache is cleaned up. Secondly, we reduce the number of ThreadLocal.get() accesses by returning a ThreadLocalStack.ThreadLocalStackReference which a client uses to pop a value. Lastly, the ThreadLocal instance is configured to set a new initial value by default. This is safe when RequestScopedCache is used but may lead to ThreadLocal leak when it is not. Therefore, special care needs to be take to guarantee that each ThreadLocal.get() operation has a matching ThreadLocalStack.Stack.removeIfEmpty() call (see peek()) as an example.