In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly talks about "what is the method of Java thread closure". Interested friends may wish to take a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what is the method of Java thread closure?"
The concept of thread closure
Synchronization is usually used when accessing shared variables, so the way to avoid synchronization is to reduce the use of shared data. This technique is thread closure.
The method of realizing thread closure
1:ad-hoc thread closure
This is completely controlled by the implementer's thread closure, and his thread closure is achieved entirely by the implementer. It is also the worst kind of thread closure. So let's just ignore him.
2: stack closed
Stack closure is the most common thread closure we encounter in programming. What is stack closure? To put it simply, it is a local variable. Multiple threads access a method, and the local variables in this method are copied to the thread stack. So local variables are not shared by multiple threads, so there is no concurrency problem. So if you can use local variables, don't use global variables. Global variables are easy to cause concurrency problems.
3:ThreadLocal closure
Using ThreadLocal is the best way to achieve thread closure, interested friends can study the source code of ThreadLocal, in fact, we can understand that ThreadLocal internal maintenance of a Map,Map key is the name of each thread, and the value of Map is the object we want to close. The object in each thread corresponds to a value in Map, that is, ThreadLocal uses Map to achieve thread closure of the object.
Detailed explanation of thread closure
Thread closure: synchronization is usually required when accessing shared variable data. One way to avoid synchronization is not to share data. Synchronization is not required if data is accessed only in a single thread, a technique called thread closure (thread confinement)
A common application of thread closure technology is the Connection object of JDBC. The JDBC specification does not require that the Connection object must be thread-safe. In the server application, the thread gets a Connection object from the connection pool and returns the object to the connection pool after use. Here are several thread closure techniques:
1. Ad-hoc thread closure
Ad-hoc thread closure means that the responsibility of maintaining thread closure is entirely borne by the program implementation, so it is very fragile to use as little as possible in the program, generally using stronger thread closure techniques, such as stack closure or ThreadLocal class.
2. Stack closure
Stack closure is a special column of thread closure. In stack closure, objects can only be accessed through local variables. One of the inherent properties of local variables is that they are enclosed in the execution stack, which can not be accessed by other threads. Stack closure is also known as thread internal use or thread local use. To put it simply, it is a local variable. Multiple threads access a method, and the local variables in this method are copied to the thread stack. So local variables are not shared by multiple threads, so there is no concurrency problem. So if you can use local variables, don't use global variables. Global variables are easy to cause concurrency problems.
For example, the following example:
Public int loadTheArk (Collection candidates) {SortedSet animals; int numPairs = 0; Animal candidate= null; / / animals is encapsulated in the method, do not overflow them animals = new TreeSet (new SpeciesGenderComparator ()); animals.addAll (candidates); for (Animal a:animals) {if (candidate==null | |! candidate.isPotentialMate (a)) {candidate= a;} else {ark.load (new AnimalPair (candidate,a); + + numPairs; candidate= null;}} return numPairs;}
Instantiate a TreeSet object in loadTheArk and save a reference to that object in animals. At this point, there is only one reference to the collection animals, which is enclosed in the local variable and therefore in the local variable. However, if a reference to the collection animals (or any internal data in the object) is published, the closure will be broken and cause the object animals to escape.
3. ThreadLocal class
A more standardized way to maintain thread closeness is to use the ThreadLocal class, which associates a value in the thread with the object that holds the value. The ThreadLocal class provides access interfaces or methods such as get and set, which have a separate copy for each thread using this variable, so get always puts back the latest value set by the current thread of execution when calling set. Take a look at the following code example:
Public class ConnectionManager {private static ThreadLocal connectionHolder = new ThreadLocal () {public Connection initialValue () {Connection conn = null; try {conn = DriverManager.getConnection ("jdbc:mysql://localhost:3306/test", "username", "password");} catch (SQLException e) {e.printStackTrace ();} return conn;}}; public static Connection getConnection () {return connectionHolder.get ();} public static void setConnection (Connection conn) {connectionHolder.set (conn);}}
By calling the ConnectionManager.getConnection () method, each thread gets a copy of its own Connection object, which is first set through the return value of the initialValue () method. Connection objects that are set through the ConnectionManager.setConnection (Connection conn) method will only be bound to the current thread. This enables complete isolation of Connection objects across multiple threads. When managing Connection objects in a multithreaded environment in a Spring container, the idea is very similar to the above code.
How is each thread bound to a copy of the Connection object? Where to keep a copy of this object. When a thread first calls the get method of the ThreadLocal class, it calls initialValue to get the initial value. Conceptually, we can think of ThreadLocal as containing a Map object that holds thread-specific values, but this is not the case with the implementation of ThreadLocal, just for our convenience.
Let's analyze the source code of the ThreadLocal class. ThreadLocal class methods are very simple, there are only four, respectively, set,get,remove, initialValue, we can literally understand the role of these methods.
Public T get (): returns the local variable corresponding to the current thread.
Public void set (T arg0): sets the value of the local variable for the current thread.
Public void remove (): removes the value of the current thread local variable in order to reduce the memory footprint, which is a new method in JDK 5.0. Note that when the thread ends, the local variables corresponding to the thread are automatically garbage collected, so it is not necessary to explicitly call this method to clear the thread's local variables, but it can speed up memory collection.
Protected T initialValue (): initializes the local variable of the current thread and returns the initial value. Is the protected property, which is obviously overridden by the subclass, only when the set and get methods are called for the first time.
Let's analyze the source code of these four methods to see how the ThreadLocal class implements this "provide a different copy of variables for each thread".
3.1 set method
The following is the source code for the set method
Public void set (T arg0) {Thread arg1 = Thread.currentThread (); ThreadLocal.ThreadLocalMap arg2 = this.getMap (arg1); if (arg2! = null) {arg2.set (this, arg0);} else {this.createMap (arg1, arg0);}}
As you can see from the set method, first get the current thread: Thread arg1 = Thread.currentThread ()
Then get the ThreadLocalMap:ThreadLocal.ThreadLocalMap arg2 = this.getMap (arg1) of the current thread
To determine whether ThreadLocalMap is empty or not, the value is set in the form of a key-value pair. Key is this,value, which is a copy of the local variable, and this is the ThreadLocal class instantiated object held by the current thread.
If empty, it is created by the createMap method.
Let's look at the source code for the getMap and createMap methods:
ThreadLocal.ThreadLocalMap getMap (Thread arg0) {return arg0.threadLocals;} void createMap (Thread arg0, T arg1) {arg0.threadLocals = new ThreadLocal.ThreadLocalMap (this, arg1);}
It is clear from the code that each thread has its own copy of the local variable, which is stored in ThreadLocalMap, where the key value is the ThreadLocal class instantiated object. That is, each thread has its own ThreadLocalMap,ThreadLocalMap that holds a copy of the local variable. Let's take a look at the java.lang.Thread source.
Private static int threadInitNumber;ThreadLocalMap threadLocals = null;ThreadLocalMap inheritableThreadLocals = null
3.2 get method
Public T get () {Thread arg0 = Thread.currentThread (); ThreadLocal.ThreadLocalMap arg1 = this.getMap (arg0); if (arg1! = null) {ThreadLocal.ThreadLocalMap.Entry arg2 = arg1.getEntry (this); if (arg2! = null) {Object arg3 = arg2.value; return arg3;}} return this.setInitialValue ();}
From the point of view of the code, the first two steps and the set method are the same, getting the ThreadLocalMap of the current thread and the current thread respectively, and the third step is to determine whether the ThreadLocalMap is empty, not to get the value according to the this key value, and to use the setInitialValue () method for air conditioning.
The following is the setInitialValue method code:
Private T setInitialValue () {Object arg0 = this.initialValue (); Thread arg1 = Thread.currentThread (); ThreadLocal.ThreadLocalMap arg2 = this.getMap (arg1); if (arg2! = null) {arg2.set (this, arg0);} else {this.createMap (arg1, arg0);} return arg0;}
The initialValue () method is called in setInitialValue, that is, the method to be overridden by the subclass, and the code corresponding to the above example is:
Protected Connection initialValue () {Connection conn = null; try {conn = DriverManager.getConnection ("jdbc:mysql://localhost:3306/test", "username", "password");} catch (SQLException e) {e.printStackTrace ();} return conn;}
Then get the current thread and the current thread's ThreadLocalMap,ThreadLocalMap is empty, then call createMap, otherwise call the set method.
At this point, I believe you have a deeper understanding of "what is the method of Java thread closure". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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.