
- Java.lang - Home
- Java.lang - Boolean
- Java.lang - Byte
- Java.lang - Character
- Java.lang - Character.Subset
- Java.lang - Character.UnicodeBlock
- Java.lang - Class
- Java.lang - ClassLoader
- Java.lang - Compiler
- Java.lang - Double
- Java.lang - Enum
- Java.lang - Float
- Java.lang - InheritableThreadLocal
- Java.lang - Integer
- Java.lang - Long
- Java.lang - Math
- Java.lang - Number
- Java.lang - Object
- Java.lang - Package
- Java.lang - Process
- Java.lang - ProcessBuilder
- Java.lang - Runtime
- Java.lang - RuntimePermission
- Java.lang - SecurityManager
- Java.lang - Short
- Java.lang - StackTraceElement
- Java.lang - StrictMath
- Java.lang - String
- Java.lang - StringBuffer
- Java.lang - StringBuilder
- Java.lang - System
- Java.lang - Thread
- Java.lang - ThreadGroup
- Java.lang - ThreadLocal
- Java.lang - Throwable
- Java.lang - Void
- Java.lang Package Useful Resources
- Java.lang - Useful Resources
- Java.lang - Discussion
Java ThreadLocal Class
Introduction
The Java ThreadLocal class provides thread-local variables.
Class Declaration
Following is the declaration for java.lang.ThreadLocal class −
public class ThreadLocal<T> extends Object
Class constructors
Sr.No. | Constructor & Description |
---|---|
1 |
ThreadLocal() This creates a thread local variable. |
Class methods
Sr.No. | Method & Description |
---|---|
1 |
T get()
This method returns the value in the current thread's copy of this thread-local variable. |
2 |
protected T initialValue()
This method returns the current thread's "initial value" for this thread-local variable. |
3 |
void remove()
This method removes the current thread's value for this thread-local variable. |
4 |
void set(T value)
This method sets the current thread's copy of this thread-local variable to the specified value. |
Methods inherited
This class inherits methods from the following classes −
- java.lang.Object
Example: Getting a Value from ThreadLocal Object
The following example shows the usage of Java ThreadLocal get() method. In this program, we've initialized a ThreadLocal object. Using set() method, a value is assigned to ThreadLocal object and using get() method, value is retrieved and printed.
package com.tutorialspoint; public class ThreadLocalDemo { public static void main(String[] args) { ThreadLocal<Integer> tlocal = new ThreadLocal<Integer>(); tlocal.set(100); // returns the current thread's value System.out.println("value = " + tlocal.get()); tlocal.set(90); // returns the current thread's value of System.out.println("value = " + tlocal.get()); } }
Output
Let us compile and run the above program, this will produce the following result −
value = 100 value = 90