Over a million developers have joined DZone.

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.

· Java Zone

Navigate the Maze of the End-User Experience and pick up this APM Essential guide, brought to you in partnership with CA Technologies

ThreadLocal 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;
  }
}

Thrive in the application economy with an APM model that is strategic. Be E.P.I.C. with CA APM.  Brought to you in partnership with CA Technologies.

Topics:
java ,threadlocal ,threading

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}