Threadlocal and local variables __ local variables

Source: Internet
Author: User

What's the difference between threadlocal and thread-local variables, let's look at a piece of code, as follows:

public class Threadlocallearn {static threadlocal<intholder> tl = new threadlocal<intholder> () {
        Protected IntHolder InitialValue () {Return to New IntHolder ();

    }

    }; public static void Main (String args[]) {for (int i=0; i<5; i++) {thread th = new Thread (new thre
            ADTest (TL, i));
        Th.start ();
    Class ThreadTest implements runnable{threadlocal<intholder> tl;//threadlocal variable int i; int a = 3;
        Thread local variable public threadtest (threadlocal<intholder> tl, int i) {super ();
        this.tl = TL;
    THIS.I = i;
        @Override public void Run () {tl.get (). Increandget ();
        a++;
        System.out.println (Tl.get (). Geta () + "");
    System.out.println ("A:" + a);

    Class intholder{int a = 1;
    public int Geta () {return A;
    public void SetA (int a) {this.a = A; } public intIncreandget () {return ++a; }
}

The code runs as follows:

2 
a:4
2 
a:4
2 
a:4
2 
a:4
2 
a:4

It can be seen that local variables and threadlocal play the same role, which ensures the security of data in concurrent environments. That is to say, can use local variable to replace threadlocal slightly, this idea is right. Let's take a look at the official description of Threadlocal:

This class provides thread-local variables. These variables differ from their normal counterparts in so each thread that accesses one (via its {@code get} or {@code Set} method) has its own, independently initialized copy of the variable. {@code ThreadLocal} instances are typically private static fields in classes-Wish to associate state with a thread (E . G., a user ID or Transaction ID).

It's a translation.

Threadlocal provides a thread-local variable. The point where these variables differ from other variables is that each thread has its own relatively independent variable initialization copy when it gets the variable. Threadl:ocal instances are generally private static and can be bound to a certain state with a thread. PS: Have a better translation please advise.

So in terms of this, we know that threadlocal is not developed for multi-threaded security because local variables are safe enough. Threadlocal is designed to make it easier for threads to handle some of their own state.
You can see where the threadlocal instantiation is, and a thread has a common area. Like a bank or a person, we can put money in a bank or we can keep it at home. The existence of money in the home is a local variable, only for personal use; the existence of money in the bank is not to say can let others casually use, only we in the personal capacity to obtain. So the variables we threadlocal package are stored in a certain area of our own, allowing us to access and modify the state ourselves.
Threadlocal also provides an initialization mechanism that, when instantiated, overrides the InitialValue () method, which enables the initialization of variables.

    Method 1
    static threadlocal<intholder> tl = new threadlocal<intholder> () {

        protected IntHolder InitialValue () {return

            new IntHolder ();
        }

    };
    Method 2
    intholder  intholder = new IntHolder ();
    static threadlocal<intholder> tl = new threadlocal& Lt;intholder> () {

        protected IntHolder InitialValue () {return

            intholder;
        }

    };

Both methods one and two can implement initialization, but method two cannot guarantee the security of thread variables, because the reference copy points to the same instance, and the modification to the reference copy is equivalent to the modification of the instance.


Of course, you can also instantiate a data within a thread for threadlocal when you judge that the threadllocal fetch data is empty. As follows:

if (null = = Tl.get ()) {

    Tl.set (new IntHolder ());
}

Why do we need threadlocal to create a state of ourselves outside of ourselves? You can actually use parameters to pass internal parameters, just like I put money on my own. It should be noted here that when we define a method, it is not the more parameters the better, some common parameters, we should try to set the global, easy to maintain the system and scalability. Another point of view, the bank also has its own value, threadlocal will simplify our programming, after all, it is safe.

According to the threadlocal principle, we implement one ourselves:

Import Java.util.concurrent.ConcurrentHashMap;

public class Threadlocalvar<t> {public

    T Initvaribale () {return

        null;
    }

    Volatile Concurrenthashmap<thread, t> map = new Concurrenthashmap<thread, t> (); 

    public void put (T-t) {

        map.put (Thread.CurrentThread (), t);
    }

    Public T get () {

        T value = Map.get (Thread.CurrentThread ());
        if (null = = value) {

            t = Initvaribale ();
            if (null = t) {return
                null;
            }
            Map.put (Thread.CurrentThread (), t);
            return t;
        } else {return

            value;
        }
    }
}

Interested can also go to read the JDK threadlocal source ~

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.