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?
Most common use of thread local is when you have some object that is not thread-safe, but you want to avoid synchronizing access to that object using synchronized keyword/block. Instead, give each thread its own instance of the object to work with.
Java ThreadLocal is used to create thread local variables. We know that all threads of an Object share it's variables, so the variable is not thread safe. We can use synchronization for thread safety but if we want to avoid synchronization, we can use ThreadLocal variables.
The ThreadLocal class is used to create thread local variables which can only be read and written by the same thread. For example, if two threads are accessing code having reference to same threadLocal variable then each thread will not see any modification to threadLocal variable done by other thread.
Java ThreadLocal class provides thread-local variables. It enables you to create variables that can only be read and write by the same thread. If two threads are executing the same code and that code has a reference to a ThreadLocal variable then the two threads can't see the local variable of each other.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With