Friday, November 1, 2024
Google search engine
HomeLanguagesJavaJava.lang.ThreadLocal Class in Java

Java.lang.ThreadLocal Class in Java

This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. Basically, it is another way to achieve thread safety apart from writing immutable classes. Since the Object is no more shared there is no requirement for Synchronization which can improve the scalability and performance of the application. ThreadLocal provides thread restriction which is an extension of a local variable. ThreadLocal is visible only in a single thread. No two threads can see each other’s thread-local variable. These variables are generally private static fields in classes and maintain their state inside the thread.

Note: ThreadLocal class extends Object class

Constructor: ThreadLocal(): This creates a thread-local variable.

 Methods of ThreadLocal Class

Method Action Performed
get() 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
initialValue() Returns the current thread initial value for the local thread variable. 
remove() Removes the current thread’s value for this thread-local variable. If this thread-local variable is subsequently read by the current thread, its value will be reinitialized by invoking its initialValue() method, unless its value is set by the current thread in the interim. This may result in multiple invocations of the initialValue method in the current thread
set() Sets the current thread’s copy of this thread-local variable to the specified value. Most subclasses will have no need to override this method, relying solely on the initialValue() method to set the values of thread locals.

Example 1:

Java




// Java Program to Illustrate ThreadLocal Class
// Via get() and set() Method
 
// Class
// ThreadLocalDemo
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating objects of ThreadLocal class
        ThreadLocal<Number> gfg_local
            = new ThreadLocal<Number>();
 
        ThreadLocal<String> gfg = new ThreadLocal<String>();
 
        // Now setting custom value
        gfg_local.set(100);
 
        // Returns the current thread's value
        System.out.println("value = " + gfg_local.get());
 
        // Setting the value
        gfg_local.set(90);
 
        // Returns the current thread's value of
        System.out.println("value = " + gfg_local.get());
 
        // Setting the value
        gfg_local.set(88.45);
 
        // Returns the current thread's value of
        System.out.println("value = " + gfg_local.get());
 
        // Setting the value
        gfg.set("Lazyroar");
 
        // Returning the current thread's value of
        System.out.println("value = " + gfg.get());
    }
}


Output

value = 100
value = 90
value = 88.45
value = Lazyroar

Example 2:

Java




// Java Program to Illustrate ThreadLocal Class
// Via Illustrating remove() Method
 
// Class
// ThreadLocalDemo
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating objects of ThreadLocal class
        ThreadLocal<Number> gfg_local
            = new ThreadLocal<Number>();
        ThreadLocal<String> gfg = new ThreadLocal<String>();
 
        // Setting the value
        gfg_local.set(100);
 
        // Returning the current thread's value
        System.out.println("value = " + gfg_local.get());
 
        // Setting the value
        gfg_local.set(90);
 
        // Returns the current thread's value of
        System.out.println("value = " + gfg_local.get());
 
        // Setting the value
        gfg_local.set(88.45);
 
        // Returning the current thread's value of
        System.out.println("value = " + gfg_local.get());
 
        // Setting the value
        gfg.set("Lazyroar");
 
        // Returning the current thread's value of
        System.out.println("value = " + gfg.get());
 
        // Removing value using remove() method
        gfg.remove();
 
        // Returning the current thread's value of
        System.out.println("value = " + gfg.get());
 
        // Removing value
        gfg_local.remove();
 
        // Returns the current thread's value of
        System.out.println("value = " + gfg_local.get());
    }
}


Output

value = 100
value = 90
value = 88.45
value = Lazyroar
value = null
value = null

Example 3:

Java




// Java Program to Illustrate ThreadLocal Class
// Via initialValue() Method
 
// Importing required classes
import java.lang.*;
 
// Class 1
// Helper class extending Thread class
class NewThread extends Thread {
 
    private static ThreadLocal gfg = new ThreadLocal() {
        protected Object initialValue()
        {
            return new Integer(question--);
        }
    };
 
    private static int question = 15;
    NewThread(String name)
    {
        // super keyword refers to parent class instance
        super(name);
        start();
    }
 
    // Method
    // run() method for Thread
    public void run()
    {
 
        for (int i = 0; i < 2; i++)
            System.out.println(getName() + " " + gfg.get());
    }
}
 
// Class 2
// Main class
// ThreadLocalDemo
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating threads inside main() method
        NewThread t1 = new NewThread("quiz1");
        NewThread t2 = new NewThread("quiz2");
    }
}


Output:

 

This article is contributed by Abhishek Verma. If you like Lazyroar and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the Lazyroar main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

RELATED ARTICLES

Most Popular

Recent Comments