ThreadLocal variable in Java

ThreadLocal is a class that allows having one variable to have a different value for each of the threads.

Each thread - i.e. an instance of the Thread class - there is a table of ThreadLocal variables associated with it. The table keys are references to objects of the ThreadLocal class, and the values are references to objects "captured" by ThreadLocal variables, i.e. ThreadLocal variables differ from regular variables in that each thread has its own, individually initialized variable instance. The value can be accessed through the get() or set() methods.

For example, if we declare a ThreadLocal variable: ThreadLocal<Object> locals = new ThreadLocal<Object>();. And then, in the stream, let's make locals.set(myObject), then the table key will be a reference to the locals object, and the value will be a reference to the myObject object. At the same time, for another thread it is possible to "put" a different value inside the locals.

Note that ThreadLocal isolates object references, not the objects themselves. If links isolated within streams point to the same object, collisions are possible.

It is also important to note that since ThreadLocal variables are isolated in threads, then the initialization of such a variable must occur in the same thread in which it will be used. It is an error to initialize such a variable (call the set() method) in the main thread of the application, because in this case the value passed in the set() method will be "captured" for the main thread, and when the get() method is called in the target thread, returned null.


Read also:


Comments

Popular posts from this blog

Methods for reading XML in Java

XML, well-formed XML and valid XML

ArrayList and LinkedList in Java, memory usage and speed