Java ThreadLocal is used to create thread-local variables. In multithreaded environment all threads of an Object share its variables, so if the variable is not thread safe, we can use synchronization but if we want to avoid synchronization, we can use ThreadLocal variables.
Every thread has its own ThreadLocal variable and they can use its get() and set() methods to get the default value or change its value local to Thread. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread.
Here is a small example showing use of ThreadLocal and proving that every thread has its own copy of ThreadLocal variable.

public class ThreadLocalExample
{
    // SimpleDateFormat is not thread-safe, so give one to each thread
    private static final ThreadLocal formatter = new ThreadLocal(){
        @Override
        protected SimpleDateFormat initialValue()
        {
            return new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
        }
    };

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

 

Thanks for your reading. Please leave a comment.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

Leave a Reply

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