So I just saw someone try to use a ThreadLocal<AtomicInteger>
in some Java code.
Now, for the linked code, that's clearly useless, among other problems which caused the request to be denied.
And it seems like it would always be useless: AtomicInteger
(from the java.util.concurrent.atomic package) is designed for multithread access, and ThreadLocal
makes each thread have its own value, so why even use it?
My question is: Is there any situation in which a ThreadLocal<AtomicInteger>
would be useful?
I think there are only exotic reasons for
ThreadLocal<AtomicInteger>
. There might be situations where theThreadLocal
is not the only reference to theAtomicInteger
so that more threads can access it. When you find yourself in such a situation, I think you better have a careful look at your design...In case you do not need the thread safety of
AtomicInteger
but merely its mutability, I prefer using anint[]
. Less overhead thenAtomicInteger
combined with full control:Yes, we may come up with a legitimate scenario:
AtomicInteger
at the start of each task;Without assessing the totality of the context where this appears, we cannot judge.
Suppose we need an integer counter per thread. ThreadLocal can work only with objects so logically we need to use an int wrapper - Integer
alternatavely we can use AtomicInteger, not because it's thread safe but because it's mutable
Version 2 has a much better performance than version 1 which is a real performance killer