Using ThreadLocal to access variables for each thread

If you would like to keep your variables’ values separate from different threads and would also like to access the variables without having to pass them as parameters then a good way would be to use the ThreadLocal. ThreadLocal is used for thread-local variables. Here is an example on how to use it.

Create the following class as below

public class ThreadLocalManager {
	public static final ThreadLocal<Integer> age = new ThreadLocal<Integer>();
	public static final ThreadLocal<String> name = new ThreadLocal<String>();
}

Then you can set the variable

ThreadLocalManager.age.set(22);
ThreadLocalManager.name.set("John");

You can retrieve it as below

ThreadLocalManager.age.get();
ThreadLocalManager.name.get();

Leave a Reply

Your email address will not be published. Required fields are marked *