ThreadLocal vs. local variable in Runnable

Which ThreadLocal or local variable in Runnable would be preferable? For performance reasons. I hope that using a local variable will give more chances for caching the processor, etc.

+7
source share
4 answers

Which one among ThreadLocal or a local variable in Runnable would be preferable.

If you have a variable declared inside a thread class (or Runnable ) then a local variable will work and you won't need ThreadLocal .

 new Thread(new Runnable() { // no need to make this a thread local because each thread already // has their own copy of it private SimpleDateFormat format = new SimpleDateFormat(...); public void run() { ... // this is allocated per thread so no thread-local format.parse(...); ... } }).start(); 

ThreadLocal used to maintain state on each thread when you execute common code. For example, SimpleDateFormat (unfortunately) is not thread safe, so if you want to use it, you will need to save it in ThreadLocal so that each thread gets its own version of the format.

 private final ThreadLocal<SimpleDateFormat> localFormat = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat(...); } }; ... // if a number of threads run this common code SimpleDateFormat format = localFormat.get(); // now we are using the per-thread format (but we should be using Joda Time :-) format.parse(...); 

An example of when this is needed is a web request handler. Threads are distributed on Jetty ground (for example) in some kind of pool that is out of our control. A web request arrives that matches your path, so Jetty calls your handler. You must have a SimpleDateFormat object, but because of its limitations, you must create one for each thread. This is when you need ThreadLocal . When you write reentrant code that can be called by multiple threads, and you want to keep something in the thread.

If you want to pass arguments to your Runnable , then you have to create your own class, and then you can access the constructor and pass the arguments.

 new Thread(new MyRunnable("some important string")).start(); ... private static class MyRunnable implements { private final String someImportantString; public MyRunnable(String someImportantString) { this.someImportantString = someImportantString; } // run by the thread public void run() { // use the someImportantString string here ... } } 
+14
source

Whenever your program can correctly use one of the two ( ThreadLocal or a local variable), select a local variable: it will be higher.

ThreadLocal designed to store state in a thread outside the method execution area. Obviously, local variables cannot remain outside their declaration. If you need it, then when can you start using ThreadLocal .

Another option is to use synchronized to control access to a shared member variable. This is a complex topic, and I will not go into it here, because it has been explained and documented by more articulated people than I do in other places. Obviously, this is not an option of "local" storage - you would share access to one resource in a thread-safe way.

+3
source

This question is answered by a simple rule, according to which a variable should be declared in the smallest possible scope. A ThreadLocal is the largest possible scope, so you should only use it for data that is needed in many lexical areas. If it is a local variable, it should be.

+1
source

I was also confused why I need ThreadLocal when I can just use local variables as they both keep their state inside the thread. But after a lot of searching and experimenting, I see why ThreadLocal is required.

I have found two applications so far -

  • Saving specific stream values โ€‹โ€‹inside the same shared object
  • An alternative to passing variables as parameters through N-levels of code

1

If you have two threads running on the same object, and both threads modify this object - then both threads continue to lose their modifications to each other.

In order for this object to have two separate states for each thread, we declare this object or its part ThreadLocal.

Of course, ThreadLocal is only useful because both threads use the same object. If they use different objects, there is no need for ThreadLocal objects.

2

The second advantage of ThreadLocal seems to be a side effect of its implementation.

The ThreadLocal variable can be a .set () stream, and then be .get () anywhere else else..get () will receive the same value that this thread set elsewhere. We will need a globally accessible shell to execute .get () and .set () to actually write the code.

When we do threadLocalVar.set () - it is as if it was placed in some kind of global "map", where this current thread is the key.

As if - someGlobalMap.put (Thread.currentThread (), threadLocalVar);

So, ten layers down when we do threadLocalVar.get () - we get the value that this thread set ten layers up.

threadLocalVar = someGlobalMap.get (Thread.currentThread ());

Thus, a function at the tenth level should not bind this variable as a parameter and can access it with .get (), without worrying about whether it is the right thread.

Finally, since the ThreadLocal variable is a copy for each thread, of course, it does not need synchronization. I misunderstood ThreadLocal earlier as an alternative to synchronization, which is not the case. Itโ€™s just a side effect of this that we donโ€™t need to synchronize the activity of this variable right now.

Hope this helps.

+1
source

Source: https://habr.com/ru/post/912985/


All Articles