FP java:S5164 ThreadLocal warning on non-static members

Rule: java:S5164
Product: SonarQube Server, Developer Edition, Version 9.9.1 (build 69595)

From what i understand about thread-locals, memory leaks as described in the rule description can only occur if the ThreadLocal is static.

Non-static thread-locals are automatically garbage-collected when the owning instance is garbage-collected.

So the rule should only apply if the ThreadLocal is static.

Example triggering false positive:

public class Foo {
    private final ThreadLocal<Object> threadLocal;
}

Hi @jmothes,

I think the problem can apply even when it’s a non-static field within your class. The ThreadLocal instance gets referenced not only by your class instance but also by an internal array within the Thread itself. As long as that thread is alive, the ThreadLocal instance will remain referenced from there. So, the potential for issues isn’t solely tied to whether the ThreadLocal field is static or not – it’s also about the lifecycle of the threads involved.

There have been real-world bugs stemming from this behavior. You can read the following GitHub issue. I think ThreadLocals are tricky. My advice would be to be extra safe with them.

But I don’t know if it leads to a bug in your case.