Which one among ThreadLocal or a local variable in Runnable will be preferred? For performance reasons. I hope using a local variable will give more chances for cpu caching, etc.
Which one among ThreadLocal or a local variable in Runnable will be preferred? For
Share
If you have a variable that is declared inside the thread’s class (or the
Runnable) then a local variable will work and you don’t need theThreadLocal.On the other hand,
ThreadLocals are used to save state on a per thread basis when you are executing common code. For example, theSimpleDateFormatis (unfortunately) not thread-safe so if you want to use it in code executed by multiple threads you would need to store one in aThreadLocalso that each thread gets it’s own version of the format.An example of when this is necessary is a web request handler. The threads are allocated up in Jetty land (for example) in some sort of pool that is outside of our control. A web request comes in which matches your path so Jetty calls your handler. You need to have a
SimpleDateFormatobject but because of its limitations, you have to create one per thread. That’s when you need aThreadLocal. When you are writing reentrant code that may be called by multiple threads and you want to store something per-thread.Instead, if you want pass in arguments to your
Runnablethen you should create your own class and then you can access the constructor and pass in arguments.