What is ThreadLocal in Java example

What is ThreadLocal in Java example –

ThreadLocal class can be used in multi threaded environment and provides thread-local variables that is local to each thread. Thread that accesses thread local variable (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread.

threadlocal

java.lang.ThreadLocal

Each thread holds an implicit reference to its copy of a thread-local variable until the thread is alive and the ThreadLocal instance is accessible. Once the thread is in dead state, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).

If you want to preserve or carry information from one method call to another you can carry it by using ThreadLocal (it is just like a thread context) and information will be available throughout the thread life cycle.

How ThreadLocal Works:

It’s just a Map of name-value pairs stored inside each Thread object (see the Thread.threadLocals field). The API hides that implementation detail, but that’s more or less all there is to it.

In the source – Thread.Java , file you can see below map declaration which is used to handle thread-locals.

/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;

Example:

Output:
Creating SimpleDateFormat for Thread : Thread-0
Creating SimpleDateFormat for Thread : Thread-1
Thread: Thread-0 Formatted Date: 09/03/2014
Thread: Thread-0 Formatted Date: 09/03/2014
Thread: Thread-1 Formatted Date: 09/03/2014
Thread: Thread-1 Formatted Date: 09/03/2014

Gopal Das
Follow me

Gopal Das

Founder at GopalDas.Org
He is a technology evangelist, Salesforce trainer, blogger, and working as a Salesforce Technical Lead. After working in Java based project implementation, he jumped to the Salesforce system on a whim and never looked back. He fell in love with Salesforce’s flexibility, scalability, and power. He expanded his knowledge of the platform and became a Certified App Builder, Administrator, Platform Developer I, SalesCloud Consultant while leading the Salesforce implementation and technology needs. He has worked in a wide variety of applications/services like desktop, web and mobile applications.
Gopal Das
Follow me

Leave a Reply

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