In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Most people do not understand the knowledge points of this article "how to use java.lang.ThreadLocal class", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to use java.lang.ThreadLocal class" article.
I. Overview
What is ThreadLocal? In fact, ThreadLocal is not a local implementation of a thread, it is not a Thread, but a threadlocalvariable (thread local variable). Perhaps it would be more appropriate to name it ThreadLocalVar. The function of thread local variable (ThreadLocal) is very simple, that is, it provides a copy of the value of the variable for every thread that uses it. It is a special thread binding mechanism in Java, where each thread can change its own copy independently without conflict with the copy of other threads.
From a thread's point of view, each thread maintains an implicit reference to its thread local variable copies, as long as the thread is active and the ThreadLocal instance is accessible; after the thread disappears, all copies of its thread local instances are garbage collected (unless there are other references to those copies).
The data accessed through ThreadLocal is always related to the current thread, that is to say, JVM binds a private local instance access space for each running thread, thus providing an isolation mechanism for concurrent access problems that often occur in a multithreaded environment.
How does ThreadLocal maintain copies of variables for each thread? In fact, the idea of implementation is simple: there is a Map in the ThreadLocal class that stores a copy of each thread's variables.
To sum up, for the problem of multi-thread resource sharing, the synchronization mechanism adopts the method of "time for space", while ThreadLocal adopts the way of "space for time". The former provides only one variable for different threads to queue up for access, while the latter provides a variable for each thread, so it can be accessed at the same time without affecting each other.
II. API description
ThreadLocal ()
Create a thread local variable.
T get ()
Returns the value in the current thread copy of this thread local variable, which is created and initialized if this is the first time the method has been called by the thread.
Protected T initialValue ()
Returns the initial value of the current thread for this thread's local variable. This method is called up to once each time the thread accesses the thread to get each thread's local variable, that is, the first time the thread uses the get () method to access the variable. If the thread calls the set (T) method before the get method, the initialValue method will not be called in the thread.
If the implementation only returns null; if the programmer wants to initialize the thread local variable to something other than null, he must create a subclass for ThreadLocal and override this method. Typically, anonymous inner classes will be used. A typical implementation of initialValue will call an appropriate constructor and return the newly constructed object.
Void remove ()
Removes the value of this thread's local variable. This may help reduce the storage requirements for thread local variables. If you access this thread local variable again, it will have its initialValue by default.
Void set (T value)
Sets the value in the current thread copy of this thread local variable to the specified value. Many applications do not need this feature and rely only on the initialValue () method to set the value of thread local variables.
The initialValue method is generally overridden in a program to give a specific initial value.
III. Typical examples
1. Hiberante's Session utility class HibernateUtil
This class is the HibernateUtil class in the Hibernate official documentation for session management.
Public class HibernateUtil {
Private static Log log = LogFactory.getLog (HibernateUtil.class)
Private static final SessionFactory sessionFactory; / / define SessionFactory
Static {
Try {
/ / create a SessionFactory through the default configuration file hibernate.cfg.xml
SessionFactory = new Configuration (). Configure (). BuildSessionFactory ()
} catch (Throwable ex) {
Log.error ("failed to initialize SessionFactory!" , ex)
Throw new ExceptionInInitializerError (ex)
}
}
/ / create a thread local variable session, which is used to hold the Session of Hibernate
Public static final ThreadLocal session = new ThreadLocal ()
/ * *
* get the Session in the current thread
* @ return Session
* @ throws HibernateException
, /
Public static Session currentSession () throws HibernateException {
Session s = (Session) session.get ()
/ / if Session is not already open, open a new Session
If (s = = null) {
S = sessionFactory.openSession ()
Session.set (s); / / Save the newly opened Session to the thread local variable
}
Return s
}
Public static void closeSession () throws HibernateException {
/ / get thread local variables and cast to Session type
Session s = (Session) session.get ()
Session.set (null)
If (s! = null)
S.close ()
}
}
In this class, since the initialValue () method of ThreadLocal is not overridden, the thread local variable session is created for the first time with an initial value of null, and the thread local variable's get () method is also null when currentSession () is called for the first time. Therefore, it is judged that if it is null, a new Session will be opened and saved to the thread local variable session, which is very critical, which is why the object session created by "public static final ThreadLocal session = new ThreadLocal ()" can be forced to be converted to a Hibernate Session object.
2. Another example
Create a Bean and set the Bean property through different thread objects to ensure the independence of each thread Bean object.
/ * *
* Created by IntelliJ IDEA.
* User: leizhimin
* Date: 2007-11-23
* Time: 10:45:02
* students
, /
Public class Student {
Private int age = 0; / / Age
Public int getAge () {
Return this.age
}
Public void setAge (int age) {
This.age = age
}
}
/ * *
* Created by IntelliJ IDEA.
* User: leizhimin
* Date: 2007-11-23
* Time: 10:53:33
* Test the program under multithreading
, /
Public class ThreadLocalDemo implements Runnable {
/ / create the thread local variable studentLocal, which you will find later to save the Student object.
Private final static ThreadLocal studentLocal = new ThreadLocal ()
Public static void main (String [] agrs) {
ThreadLocalDemo td = new ThreadLocalDemo ()
Thread T1 = new Thread (td, "a")
Thread T2 = new Thread (td, "b")
T1.start ()
T2.start ()
}
Public void run () {
AccessStudent ()
}
/ * *
* sample business method for testing
, /
Public void accessStudent () {
/ / get the name of the current thread
String currentThreadName = Thread.currentThread () .getName ()
System.out.println (currentThreadName + "is running!")
/ / generate a random number and print it
Random random = new Random ()
Int age = random.nextInt
System.out.println ("thread" + currentThreadName + "set age to:" + age)
/ / get a Student object and insert the random number age into the object property
Student student = getStudent ()
Student.setAge (age)
System.out.println ("thread" + currentThreadName + "first read age is:" + student.getAge ()
Try {
Thread.sleep (500)
}
Catch (InterruptedException ex) {
Ex.printStackTrace ()
}
System.out.println ("thread" + currentThreadName + "second read age is:" + student.getAge ()
}
Protected Student getStudent () {
/ / get local thread variables and cast to Student type
Student student = (Student) studentLocal.get ()
/ / the first time a thread executes this method, studentLocal.get () must be null
If (student = = null) {
/ / create a Student object and save it to the local thread variable studentLocal
Student = new Student ()
StudentLocal.set (student)
}
Return student
}
}
Running result:
An is running!
Thread a set age to:76
B is running!
Thread b set age to:27
Thread a first read age is:76
Thread b first read age is:27
Thread a second read age is:76
Thread b second read age is:27
You can see that the values printed by threads an and b age are exactly the same at different times. Through the ingenious use of ThreadLocal, this program not only realizes multi-thread concurrency, but also takes into account the security of data.
IV. Summary
The use of ThreadLocal mainly solves the problem of data inconsistency caused by concurrency in multi-thread. ThreadLocal provides a copy of the data accessed concurrently in each thread, and runs the business by accessing the copy, which consumes memory, greatly reduces the performance consumption caused by thread synchronization, and also reduces the complexity of thread concurrency control.
ThreadLocal cannot use atomic types, only Object types. ThreadLocal is much easier to use than synchronized.
Both ThreadLocal and Synchonized are used to address multithreaded concurrent access. But there are fundamental differences between ThreadLocal and synchronized. Synchronized uses a locking mechanism so that variables or blocks of code can only be accessed by one thread at a time. ThreadLocal provides each thread with a copy of the variable, so that each thread does not access the same object at a certain time, thus isolating the data sharing of multiple threads. Synchronized, on the other hand, is used to share data when communicating between multiple threads.
Synchronized is used for data sharing between threads, while ThreadLocal is used for data isolation between threads.
Of course, ThreadLocal is not a substitute for synchronized, they deal with different problem domains. Synchronized is used to implement synchronization mechanisms and is more complex than ThreadLocal.
V. General steps for the use of ThreadLocal
1. In a multithreaded class (such as the ThreadDemo class), create a ThreadLocal object threadXxx, which is used to hold the object xxx that needs to be isolated between threads.
2. In the ThreadDemo class, create a method getXxx () that gets the data to be accessed in isolation. If the ThreadLocal object is null, you should new () an object of isolated access type and cast to the type to be applied.
3. In the run () method of the ThreadDemo class, the data to be operated is obtained through the getXxx () method, which ensures that each thread corresponds to a data object, which is operated at any time.
The above is about the content of this article "how to use the java.lang.ThreadLocal class". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.