Java ThreadLocal
The variables which can be read and written by the same thread can be created using a class called ThreadLocal class in Java, and hence if the same code is executed by the two threads and the code is referencing to the variables of the same ThreadLocal, the two threads cannot see these variables of the ThreadLocal and therefore a code can be made thread-safe by the use of ThreadLocal class and the code would not be thread-safe without the use of ThreadLocal class and an instance of the ThreadLocal class can be created like creating the instance of any other class in java using the new operator.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
How does ThreadLocal class work in Java?
The thread-local variable is provided by java.lang.ThreadLocal class in Java. These variables are different from the normal variables so that they can be accessed by using the get or set method by each thread that is independent, own, and has a copy of the variable, which is initialized. This is basically one of the other ways to achieve the safety of the thread apart from the writing of immutable classes.
There is no more sharing of the object, and hence there is no necessity for synchronization through which the performance and scalability of the application are improved. The ThreadLocal class in Java extends the class object. The extension of the local variable, which is a restriction of the thread, is provided by the ThreadLocal class in Java. Only a single thread can view the ThreadLocal. Each other’s threads cannot see the ThreadLocal variables of two threads. The ThreadLocal variables belong to the private field, which is static in classes, and the state is maintained inside the thread.
Creation of ThreadLocal in Java
The instance of ThreadLocal is created like how an instance of any other java object is created using a new operator. Consider the below syntax to create a ThreadLocal in Java:
private ThreadLocal variable_name = new ThreadLocal();
The creation of ThreadLocal must be done only once for one thread. The values can be set and then get by multiple threads inside this ThreadLocal, and only those values set by the thread can be seen by themselves.
Get ThreadLocal value in Java
The value stored in the ThreadLocal can be read using its get() method. Consider the below syntax to get a ThreadLocal value in Java:
String variable_name = (String) threadLocal.get();
Set ThreadLocal value in Java
The value to be stored in the ThreadLocal after its creation can be set usingset() method. Consider the below syntax to set a ThreadLocal value in Java:
threadLocal.set("value_that_needs_to_be_set");
Remove ThreadLocal value in Java.
The value set in the ThreadLocal after the creation of it can be removed. The ThreadLocal value can be removed by using ThreadLocal remove() method. Consider the below syntax to remove a ThreadLocal value that is set in Java:
threadLocal.remove();
Examples to Implement Java ThreadLocal
Below are examples mentioned:
Example #1
Program to demonstrate get() method and set() method of ThreadLocal class:
Code:
//a class called demo is defined public class Demo { //main method is called public static void main(String[] args) { //an instance of the ThreadLocal is created for a number ThreadLocal<Number> local = new ThreadLocal<Number>(); //an instance of the ThreadLocal is created for a string ThreadLocal<String> val = new ThreadLocal<String>(); //setting the first number value using set() method local.set(100); //obtaining the current thread's value which returns a number using get() method System.out.println("The number value that was set is = " + local.get()); //setting the second number value using set() method local.set(90); //obtaining the current thread's value which returns a numberusing get() method System.out.println("The number value that was set is = " + local.get()); //setting the first string value using set() method val.set("Welcome to ThreadLocal"); //obtaining the current thread's value which returns a stringusing get() method System.out.println("The string value that was set is = " + val.get()); //setting the second string value using set() method val.set("Learning is fun"); //obtaining the current thread's value which returns a stringusing get() method System.out.println("The string value that was set is = " + val.get()); } }
Output:
Explanation: In the above program, a class called demo is defined. Then the main method is defined. Then an instance of the ThreadLocal is created for a number. Then an instance of the ThreadLocal is created for a string. Then the first number value is set using the set() method. Then the current thread’s value which returns a number is obtained using the get() method. Then the second numerical value is set using the set() method. Then the current thread’s value which returns a number is obtained using the get() method. Then the first string value is set using the set() method. Then the current thread’s value which returns a string is obtained using the get() method. Then the second string value is set using the set() method. Then the current thread’s value which returns a string is obtained using the get() method. The output of the program is shown in the snapshot above.
Example #2
Java program to demonstrate remove() method of ThreadLocal class:
Code:
//a class called demo is defined public class Demo { //main method is called public static void main(String[] args) { //an instance of the ThreadLocal is created for a number ThreadLocal<Number> local = new ThreadLocal<Number>(); //an instance of the ThreadLocal is created for a string ThreadLocal<String> val = new ThreadLocal<String>(); //setting the first number value using set() method local.set(100); //obtaining the current thread's value which returns a number using get() method System.out.println("The first number value that was set is = " + local.get()); //setting the second number value using set() method local.set(90); //obtaining the current thread's value which returns a number using get() method System.out.println("The second number value that was set is = " + local.get()); //setting the first string value using set() method val.set("Welcome to ThreadLocal"); //obtaining the current thread's value which returns a string using get() method System.out.println("The first string value that was set is = " + val.get()); //Using remove() method to remove the first string value that was set using set() method val.remove(); //obtaining the current thread's value which returns a string using get() method System.out.println("The first string value after using remove() method is = " + val.get()); //Using remove() method to remove the first number value and second number value that was set using set() method local.remove(); //obtaining the current thread's value using get() method System.out.println("The first number value and second number value after using remove() method is = " + local.get()); } }
Output:
Explanation: In the above program, a class called demo is defined. Then the main method is defined. Then an instance of the ThreadLocal is created for a number. Then an instance of the ThreadLocal is created for a string. Then the first number value is set using the set() method. Then the current thread’s value which returns a number is obtained using the get() method. Then the second numerical value is set using the set() method. Then the current thread’s value which returns a number is obtained using the get() method. Then the first string value is set using the set() method.
Then remove() method is used to remove the first string value that was set using the set() method. Then the current thread’s value is obtained using the get() method, and it returns null because we removed the value that was set using the remove() method. Then remove() method is used to remove the first number value and second number value that was set using the set() method. Then the current thread’s value is obtained using the get() method, and it returns null because we removed the values that were set using the remove() method. The output of the program is shown in the snapshot above.
Advantages of ThreadLocal class in Java
- ThreadLocal class makes the task of multi-threading easier because the state of the object is not shared across the threads.
- There is no need for synchronization since the state of the object is not shared across the threads.
- ThreadLocal avoids the exposure of an object to multiple threads.
Conclusion
In this tutorial, we understand ThreadLocal class’s concept through definition, working of ThreadLocal class, and their methods through programming examples and their outputs.
The above is the detailed content of Java ThreadLocal. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.
