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


You can retrieve it as below


Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.