tutorialcup
ThreadLocal in Java
ThreadLocal in Java
ThreadLocal is a Java concurrency technique where each thread has its own variables. In other words, if multiple threads read the same code, they cannot read and write on each other thread's local variables. This means that each thread can read and write only its own variables. This is the simplest way of achieving thread safety instead of creating immutable classes. The Java ThreadLocal variables are always private and static whose scope is within the thread.
Constructors of ThreadLocal
ThreadLocal has only a single constructor that creates an empty variable in Java.
ThreadLocal tl = new ThreadLocal();
Methods of ThreadLocal
Below are the methods of ThreadLocal in Java.
Benefits of ThreadLocal
- Multithreading is easier since it does not share its state across objects.
- Achieves thread-safety
- Does not require synchronization
Disadvantages of ThreadLocal
- Hides coupling among classes
- Abuses the ThreadLocal due to its visibility restriction
Example: Create, set, and get ThreadLocal
In this example, we will see how to create, set, and retrieve the value of the ThreadLocal variable. First, we create a ThreadLocal variable of Integer type. Inside the run() method, we increment the variable value and set it using the set() method. We can retrieve the value using the get() method. Using the Thread class, we create 2 threads and invoke the run() method using start().
public
ThreadLocal in Java
ThreadLocal in Java
ThreadLocal is a Java concurrency technique where each thread has its own variables. In other words, if multiple threads read the same code, they cannot read and write on each other thread's local variables. This means that each thread can read and write only its own variables. This is the simplest way of achieving thread safety instead of creating immutable classes. The Java ThreadLocal variables are always private and static whose scope is within the thread.
Constructors of ThreadLocal
ThreadLocal has only a single constructor that creates an empty variable in Java.
ThreadLocal tl = new ThreadLocal();
Methods of ThreadLocal
Below are the methods of ThreadLocal in Java.
Benefits of ThreadLocal
- Multithreading is easier since it does not share its state across objects.
- Achieves thread-safety
- Does not require synchronization
Disadvantages of ThreadLocal
- Hides coupling among classes
- Abuses the ThreadLocal due to its visibility restriction
Example: Create, set, and get ThreadLocal
In this example, we will see how to create, set, and retrieve the value of the ThreadLocal variable. First, we create a ThreadLocal variable of Integer type. Inside the run() method, we increment the variable value and set it using the set() method. We can retrieve the value using the get() method. Using the Thread class, we create 2 threads and invoke the run() method using start().
public