Purpose of ThreadLocal in Java and When to Use ThreadLocal
ThreadLocal is a simple way to have per-thread data that cannot be accessed concurrently by other threads, without requiring great effort or design compromises.
Join the DZone community and get the full member experience.
Join For FreeThreadLocal is a simple, flexible way to have per-thread data that cannot be accessed concurrently by other threads, without requiring great effort or design compromises.
A thread is a unit of execution and so multiple thread can execute the same code at the same time. If multiple threads execute on an object/instance at the same time they will share the instance variables. Each thread will have its own local variables but it is difficult to share these across objects without passing parameters.
It is best explained by way of an example. Say you have a Servlet that gets the logged in user and then executes some code.
doGet(HttpServletRequest req, HttpServletResponse resp) {
User user = getLoggedInUser(req);
doSomething()
doSomethingElse()
renderResponse(resp)
}
Now what happens if the doSomething() methods needs access to the user object? You can't make the user object an instance or static variable because each thread will then use the same user object. You could pass the user object around as a parameter but this quickly becomes messy and leaks user objects into every method call:
doGet(HttpServletRequest req, HttpServletResponse resp) {
User user = getLoggedInUser(req);
doSomething(user)
doSomethingElse(user)
renderResponse(resp,user)
}
A more elegant solution is to put the user object into a ThreadLocal
doGet(HttpServletRequest req, HttpServletResponse resp) {
User user = getLoggedInUser(req);
StaticClass.getThreadLocal().set(user)
try {
doSomething()
doSomethingElse()
renderResponse(resp)
}
finally {
StaticClass.getThreadLocal().remove()
}
}
Now any code that requires the user object at any time can get hold of it by extracting it from the thread local, without needing to resort to those pesky extra parameters:
User user = StaticClass.getThreadLocal().get()
If you use this approach be mindful to remove the objects again in a finally block. Otherwise the user object might hang around in environments that use a Thread Pool (like Tomcat app server).
The code for static class
class StaticClass {
static private ThreadLocal threadLocal = new ThreadLocal<User>();
static getThreadLocal() {
return threadLocal;
}
}
Opinions expressed by DZone contributors are their own.
Comments