Interview Questions

What is significance of using ThreadLocal?

Java Interview Questions and Answers (part 4)


(Continued from previous question...)

52. What is significance of using ThreadLocal?

This question will test your command in multi threading, can you really create some perfect multithreading application or not. ThreadLocal is a class which provides thread-local variables.

What is ThreadLocal ?
ThreadLocal is a class which provides thread-local variables. Every thread has its own ThreadLocal value that makes ThreadLocal value threadsafe as well.

For how long Thread holds ThreadLocal value?
Thread holds ThreadLocal value till it hasn’t entered dead state.

Can one thread see other thread’s ThreadLocal value?

No, thread can see only it’s ThreadLocal value.

Are ThreadLocal variables thread safe. Why?
Yes, ThreadLocal variables are thread safe. As every thread has its own ThreadLocal value and one thread can’t see other threads ThreadLocal value.

Application of ThreadLocal?
ThreadLocal are used by many web frameworks for maintaining some context (may be session or request) related value.
In any single threaded application, same thread is assigned for every request made to same action, so ThreadLocal values will be available in next request as well.
In multi threaded application, different thread is assigned for every request made to same action, so ThreadLocal values will be different for every request.

When threads have started at different time they might like to store time at which they have started. So, thread’s start time can be stored in ThreadLocal.

Creating ThreadLocal >
private ThreadLocal<String> threadLocal = new ThreadLocal<String>();

We will create instance of ThreadLocal. ThreadLocal is a generic class, i will be using String to demonstrate threadLocal.
All threads will see same instance of ThreadLocal, but a thread will be able to see value which was set by it only.

How thread set value of ThreadLocal >
threadLocal.set( new Date().toString());


Thread set value of ThreadLocal by calling set(“”) method on threadLocal.

How thread get value of ThreadLocal >
threadLocal.get()

Thread get value of ThreadLocal by calling get() method on threadLocal.

(Continued on next question...)

Other Interview Questions