What is ThreadLocal and why do we need it?! — For Automation Tester
ThreadLocal in Java is another way to achieve thread safety apart from writing immutable classes. Thread local can be considered as a scope of access like session scope or request scope. In thread local, you can set any object and this object will be local and global to the specific thread which is accessing this object.
Java ThreadLocal class provides thread-local variables. It enables you to create variables that can only be read and written 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.
How to use it?
// Declaration and Initialization
ThreadLocal threadLocal = new ThreadLocal();
// set Data
threadLocal.set(2);
// get Data
(Integer) threadLocal.get();
// remove Data
threadLocal.remove();
How does knowing about Thread-local help in Automation?
- Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class. You can use ThreadLocal in this case where your instance will be threadsafe.
- While using extent Report, you might come across scenarios where your code execution is in parallel and your test logging code breaks. At that place you can use ThreadLocal to store your extentTest and it will make logging tests easy for you.
Sorry, I’ve kept these examples short, or else you might be taking nap before reaching the end.
nevertheless, you can find more explanations about 1st Point from the links mentioned in the references & you can learn about how to use extentTest with ThreadLocal from