This is the seventh day of my participation in the August More text Challenge. For details, see:August is more challenging

concept

What a ThreadLocal does: It provides local variables within a thread that do not interfere with each other. These variables work over the life of the thread, reducing the complexity of passing some common variables between multiple functions or components within the same thread.

Conclusion:

  1. Thread concurrency: in a concurrent scenario
  2. Passing data: Through ThreadLocal in the same thread, different components pass public variables
  3. Thread isolation: Variables in each thread are independent and do not affect each other

The basic use

This is provided by the ThreadLocal JDK package, which provides thread-local variables, which means that if you create a ThreadLocal, every thread that accesses that variable will have a local copy of that variable and when multiple threads operate on that variable, they’re actually operating on their own local memory variables, This avoids thread safety problems. Once the ThreadLocal variable is created, each thread is copied to its own local.

Commonly used method

Method statement describe
ThreadLocal() Create a ThreadLocal
public void set() Sets the variable bound to the current thread
public T get() Gets the variable bound to the current thread
public void remove() Removes a variable bound to the current thread
public class MyDemo { private String data; public String getData() { return data; } public void setData(String data) { this.data = data; } public static void main(String[] args) { MyDemo myDemo = new MyDemo(); for (int i = 0; i < 5; I++) {new Thread(()->{mydemo.setdata (thread.currentthread ().getname () + "data "); System.out.println("------------------------------------"); System.out.println(Thread.currentThread().getName() + "---> " + myDemo.getData()); },String.valueOf(i)).start(); }}}Copy the code

We can see that in the concurrent scenario, the thread is not isolated, and the data set of the current thread can be accessed by other threads.

So what is thread isolation?

In a concurrent multithreaded scenario, the variables in each thread are independent of each other.

The thread of Set up the data To get the data
Thread-0 setData() Only the data set in Thread-0 can be retrieved
Thread-1 setData() Only the data set in Thread-1 can be retrieved

Use the set() method of a ThreadLocal to set variables that belong only to the current thread, but also to call the get() method of a ThreadLocal.

public class MyDemo {
    private String data;
    private final ThreadLocal<String> threadLocal = new ThreadLocal<>();
    
    public String getData(a) {
        // Get the variable bound to the current thread
        return threadLocal.get();
    }

    public void setData(String data) {
        // Set the variable bound to the current thread
        threadLocal.set(data);
    }

    public static void main(String[] args) {
        MyDemo myDemo = new MyDemo();
        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                myDemo.setData(Thread.currentThread().getName() + "Data of");
                System.out.println(Thread.currentThread().getName() + "- >"+ myDemo.getData()); },String.valueOf(i)).start(); }}}Copy the code

After using ThreadLocal, the data fetched each time is the data bound to the current thread. When a variable is maintained using a ThreadLocal, the ThreadLocal is provided for each thread that uses the variableindependentSo every thread canindependentTo change its own copy without affecting the counterparts of other threads.

ThreadLocal and Synchronized

It’s worth noting that Synchronized can do the same thing, but the way we do it is bound to cause performance problems.

Both ThreadLocal and Synchronized can be used to deal with concurrent access to variables, but from different angles

Synchronized ThreadLocal
The principle of The synchronization mechanism is “time for space”, which provides only one copy of a variable and queues threads to access it Space for Time provides each thread with a copy of a variable that can be accessed simultaneously and without interference
focus Access resource synchronization between multiple threads Multithreading isolates data from each other