Understanding thread safety from threadlocal

Source: Internet
Author: User

Seeing a lot of frames using threadlocal, it's very likely that the name will be understood as a "local thread" thing ...

First on the code:

Package Com.tiger.thread.concurrent;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Java.util.concurrent.timeunit;public class Testlocalthread {private threadlocal<integer> i = new threadlocal<integer> () {@Override protected Integer initialvalue ()        {return 0;        }    };    public void Add (int num) {i.set (I.get (). Intvalue () +num);    } public int Geti () {return i.get ();    }/*private int i = 0;    Public synchronized void Add (int num) {i + = num;    } public synchronized int Geti () {return i; }*/public static void Main (string[] args) throws Interruptedexception {final Testlocalthread t = new T                Estlocalthread ();        Executorservice es = Executors.newfixedthreadpool (2); for (int i=0;i<2;i++) {Es.execute (new Runnable () {@Override public void run () {TRY {thread.sleep (500);                    } catch (Interruptedexception e) {e.printstacktrace ();                    } t.add (1);                System.out.println (T.geti ());        }            });        } es.shutdown ();            Es.awaittermination (2, timeunit.seconds); }        }
The results are analyzed first: With threadlocal, when multiple threads are executed, each thread outputs 1,

Using the int variable directly will see that the result is the interaction between the threads, and unexpected results can occur if the normal variables are not synchronized.

When we say thread-safe, we're talking about the consistency of a certain state between threads. More directly, the variable states that multiple threads see at the same time are consistent, but in Java's memory model we can see that variables are visible to threads, meaning that at some point, when the state of a variable is not visible to other threads, It is likely that other threads are not aware of the situation and are using it in an out-of-date state.

There are several recommendations for thread safety in the Java Concurrency in practice:

1. Stateless objects must be thread-safe

2. Immutable objects must be thread-safe

3. Lock to ensure mutex and visibility

4.2 Holistic approach to thread safety: thread closure and secure publishing

A return to our example is the embodiment of these 2 ideas:

Threadlocal is to see the variable closed within the respective thread (see the source code) is not published, no state, and naturally there is no so-called synchronization control one said.

The general variable, when called by the Add () or get () method, actually publishes the state, and all threads can use it. When multiple threads are using a state and can change variables, it is important to consider the safe release of the variable, which requires a lock to ensure the visibility of the variable (of course, the atomic type can be used for secure publication to avoid the competition of the lock ).

Before seeing a lot of articles on the Internet, threadlocal and data sharing between the threads of the relationship between, personally think that may be small to understand the deviation. Threadlocal only allows variables to be consistent between threads and behavior, and is not related to state sharing.



Understanding thread safety from threadlocal

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.