ThreadLocal

Core concept of ThreadLocal is, “every thread that accesses a ThreadLocal variable via its get or set method has its own, independently initialized copy of the variable”. In this tutorial we will learn about ThreadLocal.

Table of Contents

ThreadLocal Introduction

  • We want to have separate instances(private copy) of a class so that there will not be any conflict among multiple threads. Each instance will be unique for each thread. This is nothing but a way of implementing threadsafety.
  • An important point about ThreadLocal variable is the global access. It can be accessed from anywhere inside the thread. Also note that, it is declared static and final.

What is threadsafe?

A thread is a single line of process. When we refer multi-threaded applications, we mean that there mulitple (sequential flow of control) line of process that runs through the same lines of code. In such situation, there is a possibility of one sequence(thread) accessing/modifying data of other sequence(thread). When data cannot be shared like this, then we make it threadsafe. Following are the some of the different ways of implementing threadsafe operation:

  • Re-entrancy
  • Mutual exclusion (synchronization)
  • Thread-local
  • Atomic operation

So, in the above list Thread-local is one option. Hope now we get how ThreadLocal fits in the cube.


Uses of ThreadLocal

I cannot resist but quote Joshua Bloch (who better I can choose for this section),
in his own words:

  • Genuine per-thread context, such as user id or transaction id. Works great. Easy to clean up when the thread exits the scope. No leaks.
  • Per-thread instances for performance.
  • “Sleazing” values through callbacks that you don’t control: sometimes you must call a library method that calls back into your package. At this point, you need some context that you were unable to pass to yourself, due to deficiencies in the library. In this rare situation, thread locals can be a lifesaver.


Above points, in my own terms: We have an object that is not threadsafe and we want to use it safely. We go for synchronization by enclosing that object in synchronized block. Other way around is using ThreadSafe, what it does is holds separate instance for each thread and makes it safe.

Example for ThreadLocal

package com.javapapers;

import java.text.SimpleDateFormat;
import java.util.Date;

public class ThreadLocalExample {
	private static final ThreadLocal formatter = new ThreadLocal() {

		protected SimpleDateFormat initialValue() {
			return new SimpleDateFormat("yyyyMMdd HHmm");
		}
	};

	public String formatIt(Date date) {
		return formatter.get().format(date);
	}
}

In the above sample code, get() method is key to understanding. It returns the value in the current thread’s copy of this thread-local variable. If the variable has no value for the current thread, it is first initialized to the value returned by an invocation of the initialValue method.

Example from javadoc

The class below generates unique identifiers local to each thread. A thread’s id is assigned the first time it invokes ThreadId.get() and remains unchanged on subsequent calls.

 import java.util.concurrent.atomic.AtomicInteger;

 public class ThreadId {
     // Atomic integer containing the next thread ID to be assigned
     private static final AtomicInteger nextId = new AtomicInteger(0);

     // Thread local variable containing each thread's ID
     private static final ThreadLocal threadId =
         new ThreadLocal() {
             @Override protected Integer initialValue() {
                 return nextId.getAndIncrement();
         }
     };

     // Returns the current thread's unique ID, assigning it if necessary
     public static int get() {
         return threadId.get();
     }
 }

Use of ThreadLocal in Java API

In JDK 1.7 we have got a new class namely ThreadLocalRandom. It can be used to generate random numbers specific to parallel threads. Seed for random number will be unique for each thread. This is a real cool utility.

Following is the code that implements ThreadLocal in the above class:

    private static final ThreadLocal localRandom =
        new ThreadLocal() {
            protected ThreadLocalRandom initialValue() {
                return new ThreadLocalRandom();
            }
    };

Example using ThreadLocalRandom

package com.javapapers;

import java.util.concurrent.ThreadLocalRandom;

public class ThreadLocalRandomExample {

	public static void main(String args[]) throws InterruptedException {

		//tossing 3 coins
		for (int i = 0; i < 3; i++) {
			final Thread thread = new Thread() {

				public void run() {
					System.out.print(Thread.currentThread().getName() + ":");

					// generating 3 random numbers - random for every thread
					for (int j = 0; j < 3; j++) {
						final int random = ThreadLocalRandom.current().nextInt(
								1, 3);
						System.out.print(random + ",");
					}
					System.out.println();
				}
			};
			thread.start();
			thread.join();
		}
	}
}

ThreadLocal and Memory Leaks

ThreadLocal is not evil, it is a nice utility API. It all depends on how we use it. We should learn to choose the right tool for the right situation. We cannot use cannons to burst mosquitoes, but do not blame the cannons.

There are strong complaints all over the web saying ThreadLocals will cause memory leaks. 'Mostly' No!

I wish to quote Joshua Bloch,

"...There is nothing inherently wrong with thread locals: They do not cause memory leaks. They are not slow. They are more local than their non-thread-local counterparts (i.e., they have better information hiding properties). They can be misused, of course, but so can most other programming tools...."

Why 'Mostly' No? - In case of 'self-referential structures', there is a memory leak. Refer the bug_id 6254531

This Core Java tutorial was added on 22/04/2012.

Comments on "ThreadLocal" Tutorial:

  1. Swetha says:

    cool and complete

  2. Anonymous says:

    This was very helpful..but i expect a topic on Basic Thread concept before this..

  3. Giftvincy says:

    Nice posts. This is new I have learned and very simple to read. Simplicity is your strength. Please keep on write without fail.

  4. Vijay says:

    Nice article with good explanation !

  5. Martin says:

    Pretty nice. I miss a little more information on memory leaks though. The problem with leaks thanks to ThreadLocal-s is ralated to the use of threadpools and web/app servers, redeploying etc.

  6. Jigar says:

    Nicely explain, little correction: in bug link

  7. Sandeep Singh says:

    Nice explanation

  8. Joe says:

    Thanks Jigar, I have fixed the link now.

  9. Mario Guerrero says:

    Good explain.. thanks

  10. Weng Fu says:

    Can you provide the example with Visual Basic please

  11. santhana says:

    Really nice article…i appreciate your good work….Keep it up…

  12. Rick says:

    Thanks, well written.

  13. dipesh says:

    good one

  14. Faiz says:

    nice…………article

  15. Mukesh says:

    This is really good example

  16. ninod says:

    Cool stuff and good coverage .Its nice to visit low level details with right amount of coverage

  17. KB says:

    Good job man. But what worries me is Java is like a dying language, .NET is catching up fast. Us Java programmers are getting old.

  18. Nikhil says:

    Java is Father of all language so .Net is child its coping from java only ……ya man its inheriting from java…

  19. Prabir says:

    Really I like this post. It clears my understanding about ThreadLocal class.

  20. Priya says:

    This is very useful to understand threads concepts…….

    Priyagavas

  21. Venkat says:

    Good article

  22. shweta says:

    very good
    can any one answer “Why Wait() and Notify () methods are part of the Object Class and Not Thread class?????????? “

  23. Gemini says:

    HI Joe,

    I like the way you explain the concepts. Yes, generalisation of anything makes it easy to understand. It will be more easier if you give some real time examples and illustrations.
    Good Work…!

  24. Gaurav says:

    I still didn’t understand the concept of thread local.
    This time you have not explained in better and easier way.

  25. Gaurav says:

    Can you explain what is difference between using Thread Local and Synchronization. You neither focus on when to use Thread Local or when to use synchronization.
    Moreover when we have synchronization, why should we use Thread Local.

    I am very confused after reading.
    Please clear my doubts.
    Thanks.

  26. Ajay K says:

    The article is quite confusing which talks only about the behavior of the local threads accessing its own stack of values.

    As per my suggestions, the article should include the output of the given code as well. Also, threading concepts should be elaborated enough to get the right picture of multithreading concepts as well.

    Thanks.

  27. Swami says:

    Local and Synchronization. You neither focus on when to use Thread Local or when to use synchronization.
    Moreover when we have synchronization, why should we use Thread Local.

  28. Anant Murty says:

    Hi,

    Great article!
    One thing I’d like to see is if you could explain when the ThreadLocal object can/needs to be set. That is, before the threads are created, after threads are created, but before the ‘start/run’ is called, or after threads are created and ‘start/run’ is called.

    Thanks

  29. Sameer says:

    Why would Threadlocal be required for AtomicInteger ? Isn’t it thread safe itself ?

  30. Pritam Maiti says:

    Hello Joe sir, can you please mail me your email id so that I can contact you. And yes it is a very good explanation from you again :)

  31. Jay says:

    Thanks , very clear and nice explaination…

  32. Suyash says:

    Nice article, with fine explanation

  33. Subrat says:

    Yes I have this question too..

  34. Harinath says:

    Good explanation

  35. User says:

    ThreadLocal variable in Java can create serious memory leaks if it is used to store instances of classes which is loaded by a classloader other than BootStrapClassLoader. For example, stroing Java API classes on ThreadLocal will not cause memory leak in web application, but application class, which is loaded by web-app classloader will.

  36. Ayaskant says:

    Very nice post. Easy to understand. But there is a small fault in the above code example. It will not compile unless we use Generics to declare the ThreadLocal variable as follows –

    private static final ThreadLocal formatter = new ThreadLocal() {
    //–code–
    };

  37. Ayaskant says:

    The code should be –
    private static final ThreadLocal”” formatter = new ThreadLocal””()

  38. Ayaskant says:

    {

    private static final ThreadLocal formatter = new ThreadLocal()

    }

  39. Dude Maximus says:

    Nice article.
    However, I worry about the guy above that wanted a Visual Basic example.
    For so many reasons….

  40. Abhishek says:

    Very Informative Article Sir !!
    and I have a question for you..
    I came to know that there can be a deadlock situation with single thread… Is that possible ??

    Could you please explain it in brief!!

Comments are closed for this "ThreadLocal" tutorial.

↑ Go to top