Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could ThreadLocal<AtomicInteger> possibly be useful?

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?

like image 832
Riking Avatar asked Jun 05 '13 07:06

Riking


People also ask

Should we use ThreadLocal?

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.

Why do we need ThreadLocal?

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.

What is ThreadLocal class how and why you should use it?

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.

What is valid about ThreadLocal?

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.


1 Answers

Yes, we may come up with a legitimate scenario:

  1. we need a thread-local instance of AtomicInteger at the start of each task;
  2. we proceed to distribute this object among several other threads, for example child threads forked by the main task thread.

Without assessing the totality of the context where this appears, we cannot judge.

like image 183
Marko Topolnik Avatar answered Oct 28 '22 04:10

Marko Topolnik